diff options
author | Devtools Arcadia <arcadia-devtools@yandex-team.ru> | 2022-02-07 18:08:42 +0300 |
---|---|---|
committer | Devtools Arcadia <arcadia-devtools@mous.vla.yp-c.yandex.net> | 2022-02-07 18:08:42 +0300 |
commit | 1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch) | |
tree | e26c9fed0de5d9873cce7e00bc214573dc2195b7 /contrib/libs/poco/Foundation/include | |
download | ydb-1110808a9d39d4b808aef724c861a2e1a38d2a69.tar.gz |
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'contrib/libs/poco/Foundation/include')
326 files changed, 62671 insertions, 0 deletions
diff --git a/contrib/libs/poco/Foundation/include/Poco/ASCIIEncoding.h b/contrib/libs/poco/Foundation/include/Poco/ASCIIEncoding.h new file mode 100644 index 0000000000..e47f615384 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ASCIIEncoding.h @@ -0,0 +1,51 @@ +// +// ASCIIEncoding.h +// +// Library: Foundation +// Package: Text +// Module: ASCIIEncoding +// +// Definition of the ASCIIEncoding class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ASCIIEncoding_INCLUDED +#define Foundation_ASCIIEncoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API ASCIIEncoding: public TextEncoding + /// 7-bit ASCII text encoding. +{ +public: + ASCIIEncoding(); + ~ASCIIEncoding(); + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_ASCIIEncoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AbstractCache.h b/contrib/libs/poco/Foundation/include/Poco/AbstractCache.h new file mode 100644 index 0000000000..37cfc25b1e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AbstractCache.h @@ -0,0 +1,366 @@ +// +// AbstractCache.h +// +// Library: Foundation +// Package: Cache +// Module: AbstractCache +// +// Definition of the AbstractCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AbstractCache_INCLUDED +#define Foundation_AbstractCache_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/Mutex.h" +#include "Poco/Exception.h" +#include "Poco/FIFOEvent.h" +#include "Poco/EventArgs.h" +#include "Poco/Delegate.h" +#include "Poco/SharedPtr.h" +#include <map> +#include <set> +#include <cstddef> + + +namespace Poco { + + +template <class TKey, class TValue, class TStrategy, class TMutex = FastMutex, class TEventMutex = FastMutex> +class AbstractCache + /// An AbstractCache is the interface of all caches. +{ +public: + FIFOEvent<const KeyValueArgs<TKey, TValue >, TEventMutex > Add; + FIFOEvent<const KeyValueArgs<TKey, TValue >, TEventMutex > Update; + FIFOEvent<const TKey, TEventMutex> Remove; + FIFOEvent<const TKey, TEventMutex> Get; + FIFOEvent<const EventArgs, TEventMutex> Clear; + + typedef std::map<TKey, SharedPtr<TValue > > DataHolder; + typedef typename DataHolder::iterator Iterator; + typedef typename DataHolder::const_iterator ConstIterator; + typedef std::set<TKey> KeySet; + + AbstractCache() + { + initialize(); + } + + AbstractCache(const TStrategy& strat): _strategy(strat) + { + initialize(); + } + + virtual ~AbstractCache() + { + try + { + uninitialize(); + } + catch (...) + { + poco_unexpected(); + } + } + + void add(const TKey& key, const TValue& val) + /// Adds the key value pair to the cache. + /// If for the key already an entry exists, it will be overwritten. + { + typename TMutex::ScopedLock lock(_mutex); + doAdd(key, val); + } + + void update(const TKey& key, const TValue& val) + /// Adds the key value pair to the cache. Note that adding a NULL SharedPtr will fail! + /// If for the key already an entry exists, it will be overwritten. + /// The difference to add is that no remove or add events are thrown in this case, + /// just a simply silent update is performed + /// If the key doesnot exist the behavior is equal to add, ie. an add event is thrown + { + typename TMutex::ScopedLock lock(_mutex); + doUpdate(key, val); + } + + void add(const TKey& key, SharedPtr<TValue > val) + /// Adds the key value pair to the cache. Note that adding a NULL SharedPtr will fail! + /// If for the key already an entry exists, it will be overwritten, ie. first a remove event + /// is thrown, then a add event + { + typename TMutex::ScopedLock lock(_mutex); + doAdd(key, val); + } + + void update(const TKey& key, SharedPtr<TValue > val) + /// Adds the key value pair to the cache. Note that adding a NULL SharedPtr will fail! + /// If for the key already an entry exists, it will be overwritten. + /// The difference to add is that no remove or add events are thrown in this case, + /// just an Update is thrown + /// If the key doesnot exist the behavior is equal to add, ie. an add event is thrown + { + typename TMutex::ScopedLock lock(_mutex); + doUpdate(key, val); + } + + void remove(const TKey& key) + /// Removes an entry from the cache. If the entry is not found, + /// the remove is ignored. + { + typename TMutex::ScopedLock lock(_mutex); + Iterator it = _data.find(key); + doRemove(it); + } + + bool has(const TKey& key) const + /// Returns true if the cache contains a value for the key. + { + typename TMutex::ScopedLock lock(_mutex); + return doHas(key); + } + + SharedPtr<TValue> get(const TKey& key) + /// Returns a SharedPtr of the value. The SharedPointer will remain valid + /// even when cache replacement removes the element. + /// If for the key no value exists, an empty SharedPtr is returned. + { + typename TMutex::ScopedLock lock(_mutex); + return doGet (key); + } + + void clear() + /// Removes all elements from the cache. + { + typename TMutex::ScopedLock lock(_mutex); + doClear(); + } + + std::size_t size() + /// Returns the number of cached elements + { + typename TMutex::ScopedLock lock(_mutex); + doReplace(); + return _data.size(); + } + + void forceReplace() + /// Forces cache replacement. Note that Poco's cache strategy use for efficiency reason no background thread + /// which periodically triggers cache replacement. Cache Replacement is only started when the cache is modified + /// from outside, i.e. add is called, or when a user tries to access an cache element via get. + /// In some cases, i.e. expire based caching where for a long time no access to the cache happens, + /// it might be desirable to be able to trigger cache replacement manually. + { + typename TMutex::ScopedLock lock(_mutex); + doReplace(); + } + + std::set<TKey> getAllKeys() + /// Returns a copy of all keys stored in the cache + { + typename TMutex::ScopedLock lock(_mutex); + doReplace(); + ConstIterator it = _data.begin(); + ConstIterator itEnd = _data.end(); + std::set<TKey> result; + for (; it != itEnd; ++it) + result.insert(it->first); + + return result; + } + +protected: + mutable FIFOEvent<ValidArgs<TKey> > IsValid; + mutable FIFOEvent<KeySet> Replace; + + void initialize() + /// Sets up event registration. + { + Add += Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onAdd); + Update += Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onUpdate); + Remove += Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onRemove); + Get += Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onGet); + Clear += Delegate<TStrategy, const EventArgs>(&_strategy, &TStrategy::onClear); + IsValid += Delegate<TStrategy, ValidArgs<TKey> >(&_strategy, &TStrategy::onIsValid); + Replace += Delegate<TStrategy, KeySet>(&_strategy, &TStrategy::onReplace); + } + + void uninitialize() + /// Reverts event registration. + { + Add -= Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onAdd ); + Update -= Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onUpdate); + Remove -= Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onRemove); + Get -= Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onGet); + Clear -= Delegate<TStrategy, const EventArgs>(&_strategy, &TStrategy::onClear); + IsValid -= Delegate<TStrategy, ValidArgs<TKey> >(&_strategy, &TStrategy::onIsValid); + Replace -= Delegate<TStrategy, KeySet>(&_strategy, &TStrategy::onReplace); + } + + void doAdd(const TKey& key, const TValue& val) + /// Adds the key value pair to the cache. + /// If for the key already an entry exists, it will be overwritten. + { + Iterator it = _data.find(key); + doRemove(it); + + KeyValueArgs<TKey, TValue> args(key, val); + Add.notify(this, args); + _data.insert(std::make_pair(key, SharedPtr<TValue>(new TValue(val)))); + + doReplace(); + } + + void doAdd(const TKey& key, SharedPtr<TValue>& val) + /// Adds the key value pair to the cache. + /// If for the key already an entry exists, it will be overwritten. + { + Iterator it = _data.find(key); + doRemove(it); + + KeyValueArgs<TKey, TValue> args(key, *val); + Add.notify(this, args); + _data.insert(std::make_pair(key, val)); + + doReplace(); + } + + void doUpdate(const TKey& key, const TValue& val) + /// Adds the key value pair to the cache. + /// If for the key already an entry exists, it will be overwritten. + { + KeyValueArgs<TKey, TValue> args(key, val); + Iterator it = _data.find(key); + if (it == _data.end()) + { + Add.notify(this, args); + _data.insert(std::make_pair(key, SharedPtr<TValue>(new TValue(val)))); + } + else + { + Update.notify(this, args); + it->second = SharedPtr<TValue>(new TValue(val)); + } + + doReplace(); + } + + void doUpdate(const TKey& key, SharedPtr<TValue>& val) + /// Adds the key value pair to the cache. + /// If for the key already an entry exists, it will be overwritten. + { + KeyValueArgs<TKey, TValue> args(key, *val); + Iterator it = _data.find(key); + if (it == _data.end()) + { + Add.notify(this, args); + _data.insert(std::make_pair(key, val)); + } + else + { + Update.notify(this, args); + it->second = val; + } + + doReplace(); + } + + void doRemove(Iterator it) + /// Removes an entry from the cache. If the entry is not found + /// the remove is ignored. + { + if (it != _data.end()) + { + Remove.notify(this, it->first); + _data.erase(it); + } + } + + bool doHas(const TKey& key) const + /// Returns true if the cache contains a value for the key + { + // ask the strategy if the key is valid + ConstIterator it = _data.find(key); + bool result = false; + + if (it != _data.end()) + { + ValidArgs<TKey> args(key); + IsValid.notify(this, args); + result = args.isValid(); + } + + return result; + } + + SharedPtr<TValue> doGet(const TKey& key) + /// Returns a SharedPtr of the cache entry, returns 0 if for + /// the key no value was found + { + Iterator it = _data.find(key); + SharedPtr<TValue> result; + + if (it != _data.end()) + { + // inform all strategies that a read-access to an element happens + Get.notify(this, key); + // ask all strategies if the key is valid + ValidArgs<TKey> args(key); + IsValid.notify(this, args); + + if (!args.isValid()) + { + doRemove(it); + } + else + { + result = it->second; + } + } + + return result; + } + + void doClear() + { + static EventArgs _emptyArgs; + Clear.notify(this, _emptyArgs); + _data.clear(); + } + + void doReplace() + { + std::set<TKey> delMe; + Replace.notify(this, delMe); + // delMe contains the to be removed elements + typename std::set<TKey>::const_iterator it = delMe.begin(); + typename std::set<TKey>::const_iterator endIt = delMe.end(); + + for (; it != endIt; ++it) + { + Iterator itH = _data.find(*it); + doRemove(itH); + } + } + + TStrategy _strategy; + mutable DataHolder _data; + mutable TMutex _mutex; + +private: + AbstractCache(const AbstractCache& aCache); + AbstractCache& operator = (const AbstractCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_AbstractCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AbstractDelegate.h b/contrib/libs/poco/Foundation/include/Poco/AbstractDelegate.h new file mode 100644 index 0000000000..9dea69a364 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AbstractDelegate.h @@ -0,0 +1,110 @@ +// +// AbstractDelegate.h +// +// Library: Foundation +// Package: Events +// Module: AbstractDelegate +// +// Implementation of the AbstractDelegate template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AbstractDelegate_INCLUDED +#define Foundation_AbstractDelegate_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template <class TArgs> +class AbstractDelegate + /// Base class for Delegate and Expire. +{ +public: + AbstractDelegate() + { + } + + AbstractDelegate(const AbstractDelegate& /*del*/) + { + } + + virtual ~AbstractDelegate() + { + } + + virtual bool notify(const void* sender, TArgs& arguments) = 0; + /// Invokes the delegate's callback function. + /// Returns true if successful, or false if the delegate + /// has been disabled or has expired. + + virtual bool equals(const AbstractDelegate& other) const = 0; + /// Compares the AbstractDelegate with the other one for equality. + + virtual AbstractDelegate* clone() const = 0; + /// Returns a deep copy of the AbstractDelegate. + + virtual void disable() = 0; + /// Disables the delegate, which is done prior to removal. + + virtual const AbstractDelegate* unwrap() const + /// Returns the unwrapped delegate. Must be overridden by decorators + /// like Expire. + { + return this; + } +}; + + +template <> +class AbstractDelegate<void> + /// Base class for Delegate and Expire. +{ +public: + AbstractDelegate() + { + } + + AbstractDelegate(const AbstractDelegate&) + { + } + + virtual ~AbstractDelegate() + { + } + + virtual bool notify(const void* sender) = 0; + /// Invokes the delegate's callback function. + /// Returns true if successful, or false if the delegate + /// has been disabled or has expired. + + virtual bool equals(const AbstractDelegate& other) const = 0; + /// Compares the AbstractDelegate with the other one for equality. + + virtual AbstractDelegate* clone() const = 0; + /// Returns a deep copy of the AbstractDelegate. + + virtual void disable() = 0; + /// Disables the delegate, which is done prior to removal. + + virtual const AbstractDelegate* unwrap() const + /// Returns the unwrapped delegate. Must be overridden by decorators + /// like Expire. + { + return this; + } +}; + + +} // namespace Poco + + +#endif // Foundation_AbstractDelegate_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AbstractEvent.h b/contrib/libs/poco/Foundation/include/Poco/AbstractEvent.h new file mode 100644 index 0000000000..917092a9a0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AbstractEvent.h @@ -0,0 +1,558 @@ +// +// AbstractEvent.h +// +// Library: Foundation +// Package: Events +// Module: AbstractEvent +// +// Definition of the AbstractEvent class. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AbstractFoundation_INCLUDED +#define Foundation_AbstractFoundation_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/SingletonHolder.h" +#include "Poco/SharedPtr.h" +#include "Poco/ActiveResult.h" +#include "Poco/ActiveMethod.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class TArgs, class TStrategy, class TDelegate, class TMutex = FastMutex> +class AbstractEvent + /// An AbstractEvent is the base class of all events. + /// It works similar to the way C# handles notifications (aka events in C#). + /// + /// Events can be used to send information to a set of delegates + /// which are registered with the event. The type of the data is specified with + /// the template parameter TArgs. The TStrategy parameter must be a subclass + /// of NotificationStrategy. The parameter TDelegate can either be a subclass of AbstractDelegate + /// or of AbstractPriorityDelegate. + /// + /// Note that AbstractEvent should never be used directly. One ought to use + /// one of its subclasses which set the TStrategy and TDelegate template parameters + /// to fixed values. For most use-cases the BasicEvent template will be sufficient: + /// + /// #include "Poco/BasicEvent.h" + /// #include "Poco/Delegate.h" + /// + /// Note that as of release 1.4.2, the behavior of BasicEvent equals that of FIFOEvent, + /// so the FIFOEvent class is no longer necessary and provided for backwards compatibility + /// only. + /// + /// BasicEvent works with a standard delegate. They allow one object to register + /// one or more delegates with an event. In contrast, a PriorityDelegate comes with an attached priority value + /// and allows one object to register for one priority value one or more delegates. Note that PriorityDelegates + /// only work with PriorityEvents: + /// + /// #include "Poco/PriorityEvent.h" + /// #include "Poco/PriorityDelegate.h" + /// + /// Use events by adding them as public members to the object which is throwing notifications: + /// + /// class MyData + /// { + /// public: + /// Poco::BasicEvent<int> dataChanged; + /// + /// MyData(); + /// ... + /// void setData(int i); + /// ... + /// private: + /// int _data; + /// }; + /// + /// Firing the event is done either by calling the event's notify() or notifyAsync() method: + /// + /// void MyData::setData(int i) + /// { + /// this->_data = i; + /// dataChanged.notify(this, this->_data); + /// } + /// + /// Alternatively, instead of notify(), operator () can be used. + /// + /// void MyData::setData(int i) + /// { + /// this->_data = i; + /// dataChanged(this, this->_data); + /// } + /// + /// Note that operator (), notify() and notifyAsync() do not catch exceptions, i.e. in case a + /// delegate throws an exception, notifying is immediately aborted and the exception is propagated + /// back to the caller. + /// + /// Delegates can register methods at the event. In the case of a BasicEvent + /// the Delegate template is used, in case of an PriorityEvent a PriorityDelegate is used. + /// Mixing of delegates, e.g. using a PriorityDelegate with a BasicEvent is not allowed and + /// can lead to compile-time and/or run-time errors. The standalone delegate() functions + /// can be used to construct Delegate objects. + /// + /// Events require the observers to have one of the following method signatures: + /// + /// void onEvent(const void* pSender, TArgs& args); + /// void onEvent(TArgs& args); + /// static void onEvent(const void* pSender, TArgs& args); + /// static void onEvent(void* pSender, TArgs& args); + /// static void onEvent(TArgs& args); + /// + /// For performance reasons arguments are always sent by reference. This also allows observers + /// to modify the event argument. To prevent that, use <[const TArg]> as template + /// parameter. A non-conformant method signature leads to compile errors. + /// + /// Assuming that the observer meets the method signature requirement, it can register + /// this method with the += operator: + /// + /// class MyController + /// { + /// protected: + /// MyData _data; + /// + /// void onDataChanged(void* pSender, int& data); + /// ... + /// }; + /// + /// MyController::MyController() + /// { + /// _data.dataChanged += delegate(this, &MyController::onDataChanged); + /// } + /// + /// In some cases it might be desirable to work with automatically expiring registrations. Simply add + /// to delegate as 3rd parameter a expireValue (in milliseconds): + /// + /// _data.dataChanged += delegate(this, &MyController::onDataChanged, 1000); + /// + /// This will add a delegate to the event which will automatically be removed in 1000 millisecs. + /// + /// Unregistering happens via the -= operator. Forgetting to unregister a method will lead to + /// segmentation faults later, when one tries to send a notify to a no longer existing object. + /// + /// MyController::~MyController() + /// { + /// _data.dataChanged -= delegate(this, &MyController::onDataChanged); + /// } + /// + /// Working with PriorityDelegate's as similar to working with BasicEvent. + /// Instead of delegate(), the priorityDelegate() function must be used + /// to create the PriorityDelegate. +{ +public: + typedef TDelegate* DelegateHandle; + typedef TArgs Args; + + AbstractEvent(): + _executeAsync(this, &AbstractEvent::executeAsyncImpl), + _enabled(true) + { + } + + AbstractEvent(const TStrategy& strat): + _executeAsync(this, &AbstractEvent::executeAsyncImpl), + _strategy(strat), + _enabled(true) + { + } + + virtual ~AbstractEvent() + { + } + + void operator += (const TDelegate& aDelegate) + /// Adds a delegate to the event. + /// + /// Exact behavior is determined by the TStrategy. + { + typename TMutex::ScopedLock lock(_mutex); + _strategy.add(aDelegate); + } + + void operator -= (const TDelegate& aDelegate) + /// Removes a delegate from the event. + /// + /// If the delegate is not found, this function does nothing. + { + typename TMutex::ScopedLock lock(_mutex); + _strategy.remove(aDelegate); + } + + DelegateHandle add(const TDelegate& aDelegate) + /// Adds a delegate to the event. + /// + /// Exact behavior is determined by the TStrategy. + /// + /// Returns a DelegateHandle which can be used in call to + /// remove() to remove the delegate. + { + typename TMutex::ScopedLock lock(_mutex); + return _strategy.add(aDelegate); + } + + void remove(DelegateHandle delegateHandle) + /// Removes a delegate from the event using a DelegateHandle + /// returned by add(). + /// + /// If the delegate is not found, this function does nothing. + { + typename TMutex::ScopedLock lock(_mutex); + _strategy.remove(delegateHandle); + } + + void operator () (const void* pSender, TArgs& args) + /// Shortcut for notify(pSender, args); + { + notify(pSender, args); + } + + void operator () (TArgs& args) + /// Shortcut for notify(args). + { + notify(0, args); + } + + void notify(const void* pSender, TArgs& args) + /// Sends a notification to all registered delegates. The order is + /// determined by the TStrategy. This method is blocking. While executing, + /// the list of delegates may be modified. These changes don't + /// influence the current active notifications but are activated with + /// the next notify. If a delegate is removed during a notify(), the + /// delegate will no longer be invoked (unless it has already been + /// invoked prior to removal). If one of the delegates throws an exception, + /// the notify method is immediately aborted and the exception is propagated + /// to the caller. + { + Poco::ScopedLockWithUnlock<TMutex> lock(_mutex); + + if (!_enabled) return; + + // thread-safeness: + // copy should be faster and safer than blocking until + // execution ends + TStrategy strategy(_strategy); + lock.unlock(); + strategy.notify(pSender, args); + } + + bool hasDelegates() const { + return !empty(); + } + + ActiveResult<TArgs> notifyAsync(const void* pSender, const TArgs& args) + /// Sends a notification to all registered delegates. The order is + /// determined by the TStrategy. This method is not blocking and will + /// immediately return. The delegates are invoked in a seperate thread. + /// Call activeResult.wait() to wait until the notification has ended. + /// While executing, other objects can change the delegate list. These changes don't + /// influence the current active notifications but are activated with + /// the next notify. If a delegate is removed during a notify(), the + /// delegate will no longer be invoked (unless it has already been + /// invoked prior to removal). If one of the delegates throws an exception, + /// the execution is aborted and the exception is propagated to the caller. + { + NotifyAsyncParams params(pSender, args); + { + typename TMutex::ScopedLock lock(_mutex); + + // thread-safeness: + // copy should be faster and safer than blocking until + // execution ends + // make a copy of the strategy here to guarantee that + // between notifyAsync and the execution of the method no changes can occur + + params.ptrStrat = SharedPtr<TStrategy>(new TStrategy(_strategy)); + params.enabled = _enabled; + } + ActiveResult<TArgs> result = _executeAsync(params); + return result; + } + + void enable() + /// Enables the event. + { + typename TMutex::ScopedLock lock(_mutex); + _enabled = true; + } + + void disable() + /// Disables the event. notify and notifyAsnyc will be ignored, + /// but adding/removing delegates is still allowed. + { + typename TMutex::ScopedLock lock(_mutex); + _enabled = false; + } + + bool isEnabled() const + { + typename TMutex::ScopedLock lock(_mutex); + return _enabled; + } + + void clear() + /// Removes all delegates. + { + typename TMutex::ScopedLock lock(_mutex); + _strategy.clear(); + } + + bool empty() const + /// Checks if any delegates are registered at the delegate. + { + typename TMutex::ScopedLock lock(_mutex); + return _strategy.empty(); + } + +protected: + struct NotifyAsyncParams + { + SharedPtr<TStrategy> ptrStrat; + const void* pSender; + TArgs args; + bool enabled; + + NotifyAsyncParams(const void* pSend, const TArgs& a):ptrStrat(), pSender(pSend), args(a), enabled(true) + /// Default constructor reduces the need for TArgs to have an empty constructor, only copy constructor is needed. + { + } + }; + + ActiveMethod<TArgs, NotifyAsyncParams, AbstractEvent> _executeAsync; + + TArgs executeAsyncImpl(const NotifyAsyncParams& par) + { + if (!par.enabled) + { + return par.args; + } + + NotifyAsyncParams params = par; + TArgs retArgs(params.args); + params.ptrStrat->notify(params.pSender, retArgs); + return retArgs; + } + + TStrategy _strategy; /// The strategy used to notify observers. + bool _enabled; /// Stores if an event is enabled. Notfies on disabled events have no effect + /// but it is possible to change the observers. + mutable TMutex _mutex; + +private: + AbstractEvent(const AbstractEvent& other); + AbstractEvent& operator = (const AbstractEvent& other); +}; + + +template <class TStrategy, class TDelegate, class TMutex> +class AbstractEvent<void, TStrategy, TDelegate, TMutex> +{ +public: + typedef TDelegate* DelegateHandle; + + AbstractEvent(): + _executeAsync(this, &AbstractEvent::executeAsyncImpl), + _enabled(true) + { + } + + AbstractEvent(const TStrategy& strat): + _executeAsync(this, &AbstractEvent::executeAsyncImpl), + _strategy(strat), + _enabled(true) + { + } + + virtual ~AbstractEvent() + { + } + + void operator += (const TDelegate& aDelegate) + /// Adds a delegate to the event. + /// + /// Exact behavior is determined by the TStrategy. + { + typename TMutex::ScopedLock lock(_mutex); + _strategy.add(aDelegate); + } + + void operator -= (const TDelegate& aDelegate) + /// Removes a delegate from the event. + /// + /// If the delegate is not found, this function does nothing. + { + typename TMutex::ScopedLock lock(_mutex); + _strategy.remove(aDelegate); + } + + DelegateHandle add(const TDelegate& aDelegate) + /// Adds a delegate to the event. + /// + /// Exact behavior is determined by the TStrategy. + /// + /// Returns a DelegateHandle which can be used in call to + /// remove() to remove the delegate. + { + typename TMutex::ScopedLock lock(_mutex); + return _strategy.add(aDelegate); + } + + void remove(DelegateHandle delegateHandle) + /// Removes a delegate from the event using a DelegateHandle + /// returned by add(). + /// + /// If the delegate is not found, this function does nothing. + { + typename TMutex::ScopedLock lock(_mutex); + _strategy.remove(delegateHandle); + } + + void operator () (const void* pSender) + /// Shortcut for notify(pSender, args); + { + notify(pSender); + } + + void operator () () + /// Shortcut for notify(args). + { + notify(0); + } + + void notify(const void* pSender) + /// Sends a notification to all registered delegates. The order is + /// determined by the TStrategy. This method is blocking. While executing, + /// the list of delegates may be modified. These changes don't + /// influence the current active notifications but are activated with + /// the next notify. If a delegate is removed during a notify(), the + /// delegate will no longer be invoked (unless it has already been + /// invoked prior to removal). If one of the delegates throws an exception, + /// the notify method is immediately aborted and the exception is propagated + /// to the caller. + { + Poco::ScopedLockWithUnlock<TMutex> lock(_mutex); + + if (!_enabled) return; + + // thread-safeness: + // copy should be faster and safer than blocking until + // execution ends + TStrategy strategy(_strategy); + lock.unlock(); + strategy.notify(pSender); + } + + ActiveResult<void> notifyAsync(const void* pSender) + /// Sends a notification to all registered delegates. The order is + /// determined by the TStrategy. This method is not blocking and will + /// immediately return. The delegates are invoked in a seperate thread. + /// Call activeResult.wait() to wait until the notification has ended. + /// While executing, other objects can change the delegate list. These changes don't + /// influence the current active notifications but are activated with + /// the next notify. If a delegate is removed during a notify(), the + /// delegate will no longer be invoked (unless it has already been + /// invoked prior to removal). If one of the delegates throws an exception, + /// the execution is aborted and the exception is propagated to the caller. + { + NotifyAsyncParams params(pSender); + { + typename TMutex::ScopedLock lock(_mutex); + + // thread-safeness: + // copy should be faster and safer than blocking until + // execution ends + // make a copy of the strategy here to guarantee that + // between notifyAsync and the execution of the method no changes can occur + + params.ptrStrat = SharedPtr<TStrategy>(new TStrategy(_strategy)); + params.enabled = _enabled; + } + ActiveResult<void> result = _executeAsync(params); + return result; + } + + void enable() + /// Enables the event. + { + typename TMutex::ScopedLock lock(_mutex); + _enabled = true; + } + + void disable() + /// Disables the event. notify and notifyAsnyc will be ignored, + /// but adding/removing delegates is still allowed. + { + typename TMutex::ScopedLock lock(_mutex); + _enabled = false; + } + + bool isEnabled() const + { + typename TMutex::ScopedLock lock(_mutex); + return _enabled; + } + + void clear() + /// Removes all delegates. + { + typename TMutex::ScopedLock lock(_mutex); + _strategy.clear(); + } + + bool empty() const + /// Checks if any delegates are registered at the delegate. + { + typename TMutex::ScopedLock lock(_mutex); + return _strategy.empty(); + } + +protected: + struct NotifyAsyncParams + { + SharedPtr<TStrategy> ptrStrat; + const void* pSender; + bool enabled; + + NotifyAsyncParams(const void* pSend):ptrStrat(), pSender(pSend), enabled(true) + /// Default constructor reduces the need for TArgs to have an empty constructor, only copy constructor is needed. + { + } + }; + + ActiveMethod<void, NotifyAsyncParams, AbstractEvent> _executeAsync; + + void executeAsyncImpl(const NotifyAsyncParams& par) + { + if (!par.enabled) + { + return; + } + + NotifyAsyncParams params = par; + params.ptrStrat->notify(params.pSender); + return; + } + + TStrategy _strategy; /// The strategy used to notify observers. + bool _enabled; /// Stores if an event is enabled. Notfies on disabled events have no effect + /// but it is possible to change the observers. + mutable TMutex _mutex; + +private: + AbstractEvent(const AbstractEvent& other); + AbstractEvent& operator = (const AbstractEvent& other); +}; + + +} // namespace Poco + + +#endif // Foundation_AbstractFoundation_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AbstractObserver.h b/contrib/libs/poco/Foundation/include/Poco/AbstractObserver.h new file mode 100644 index 0000000000..baa40a66dc --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AbstractObserver.h @@ -0,0 +1,50 @@ +// +// AbstractObserver.h +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Definition of the AbstractObserver class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AbstractObserver_INCLUDED +#define Foundation_AbstractObserver_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Notification.h" + + +namespace Poco { + + +class Foundation_API AbstractObserver + /// The base class for all instantiations of + /// the Observer and NObserver template classes. +{ +public: + AbstractObserver(); + AbstractObserver(const AbstractObserver& observer); + virtual ~AbstractObserver(); + + AbstractObserver& operator = (const AbstractObserver& observer); + + virtual void notify(Notification* pNf) const = 0; + virtual bool equals(const AbstractObserver& observer) const = 0; + virtual bool accepts(Notification* pNf) const = 0; + virtual AbstractObserver* clone() const = 0; + virtual void disable() = 0; +}; + + +} // namespace Poco + + +#endif // Foundation_AbstractObserver_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AbstractPriorityDelegate.h b/contrib/libs/poco/Foundation/include/Poco/AbstractPriorityDelegate.h new file mode 100644 index 0000000000..c27bc0c3f4 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AbstractPriorityDelegate.h @@ -0,0 +1,63 @@ +// +// AbstractPriorityDelegate.h +// +// Library: Foundation +// Package: Events +// Module: AbstractPriorityDelegate +// +// Implementation of the AbstractPriorityDelegate template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AbstractPriorityDelegate_INCLUDED +#define Foundation_AbstractPriorityDelegate_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractDelegate.h" + + +namespace Poco { + + +template <class TArgs> +class AbstractPriorityDelegate: public AbstractDelegate<TArgs> + /// Base class for PriorityDelegate and PriorityExpire. + /// + /// Extends AbstractDelegate with a priority value. +{ +public: + AbstractPriorityDelegate(int prio): + _priority(prio) + { + } + + AbstractPriorityDelegate(const AbstractPriorityDelegate& del): + AbstractDelegate<TArgs>(del), + _priority(del._priority) + { + } + + virtual ~AbstractPriorityDelegate() + { + } + + int priority() const + { + return _priority; + } + +protected: + int _priority; +}; + + +} // namespace Poco + + +#endif // Foundation_AbstractPriorityDelegate_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AbstractStrategy.h b/contrib/libs/poco/Foundation/include/Poco/AbstractStrategy.h new file mode 100644 index 0000000000..8d0ac25a22 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AbstractStrategy.h @@ -0,0 +1,77 @@ +// +// AbstractStrategy.h +// +// Library: Foundation +// Package: Cache +// Module: AbstractCache +// +// Definition of the AbstractStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AbstractStrategy_INCLUDED +#define Foundation_AbstractStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/EventArgs.h" +#include <set> + + +namespace Poco { + + +template <class TKey, class TValue> +class AbstractStrategy + /// An AbstractStrategy is the interface for all strategies. +{ +public: + AbstractStrategy() + { + } + + virtual ~AbstractStrategy() + { + } + + virtual void onUpdate(const void* pSender, const KeyValueArgs <TKey, TValue>& args) + /// Updates an existing entry. + { + onRemove(pSender,args.key()); + onAdd(pSender, args); + } + + virtual void onAdd(const void* pSender, const KeyValueArgs <TKey, TValue>& key) = 0; + /// Adds the key to the strategy. + /// If for the key already an entry exists, an exception will be thrown. + + virtual void onRemove(const void* pSender, const TKey& key) = 0; + /// Removes an entry from the strategy. If the entry is not found + /// the remove is ignored. + + virtual void onGet(const void* pSender, const TKey& key) = 0; + /// Informs the strategy that a read-access happens to an element. + + virtual void onClear(const void* pSender, const EventArgs& args) = 0; + /// Removes all elements from the cache. + + virtual void onIsValid(const void* pSender, ValidArgs<TKey>& key) = 0; + /// Used to query if a key is still valid (i.e. cached). + + virtual void onReplace(const void* pSender, std::set<TKey>& elemsToRemove) = 0; + /// Used by the Strategy to indicate which elements should be removed from + /// the cache. Note that onReplace does not change the current list of keys. + /// The cache object is reponsible to remove the elements. +}; + + +} // namespace Poco + + +#endif // Foundation_AbstractStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AccessExpirationDecorator.h b/contrib/libs/poco/Foundation/include/Poco/AccessExpirationDecorator.h new file mode 100644 index 0000000000..9978185ffc --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AccessExpirationDecorator.h @@ -0,0 +1,83 @@ +// +// AccessExpirationDecorator.h +// +// Library: Foundation +// Package: Cache +// Module: AccessExpirationDecorator +// +// Implementation of the AccessExpirationDecorator template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AccessExpirationDecorator_INCLUDED +#define Foundation_AccessExpirationDecorator_INCLUDED + + +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" + + +namespace Poco { + + +template <typename TArgs> +class AccessExpirationDecorator + /// AccessExpirationDecorator adds an expiration method to values so that they can be used + /// with the UniqueAccessExpireCache +{ +public: + AccessExpirationDecorator(): + _value(), + _span() + { + } + + AccessExpirationDecorator(const TArgs& p, const Poco::Timespan::TimeDiff& diffInMs): + /// Creates an element that will expire in diff milliseconds + _value(p), + _span(diffInMs*1000) + { + } + + AccessExpirationDecorator(const TArgs& p, const Poco::Timespan& timeSpan): + /// Creates an element that will expire after the given timeSpan + _value(p), + _span(timeSpan) + { + } + + + ~AccessExpirationDecorator() + { + } + + const Poco::Timespan& getTimeout() const + { + return _span; + } + + const TArgs& value() const + { + return _value; + } + + TArgs& value() + { + return _value; + } + +private: + TArgs _value; + Timespan _span; +}; + + +} // namespace Poco + + +#endif // Foundation_AccessExpirationDecorator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AccessExpireCache.h b/contrib/libs/poco/Foundation/include/Poco/AccessExpireCache.h new file mode 100644 index 0000000000..bb5c571526 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AccessExpireCache.h @@ -0,0 +1,63 @@ +// +// AccessExpireCache.h +// +// Library: Foundation +// Package: Cache +// Module: AccessExpireCache +// +// Definition of the AccessExpireCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AccessExpireCache_INCLUDED +#define Foundation_AccessExpireCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/AccessExpireStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class AccessExpireCache: public AbstractCache<TKey, TValue, AccessExpireStrategy<TKey, TValue>, TMutex, TEventMutex> + /// An AccessExpireCache caches entries for a fixed time period (per default 10 minutes). + /// Entries expire when they are not accessed with get() during this time period. Each access resets + /// the start time for expiration. + /// Be careful when using an AccessExpireCache. A cache is often used + /// like cache.has(x) followed by cache.get x). Note that it could happen + /// that the "has" call works, then the current execution thread gets descheduled, time passes, + /// the entry gets invalid, thus leading to an empty SharedPtr being returned + /// when "get" is invoked. +{ +public: + AccessExpireCache(Timestamp::TimeDiff expire = 600000): + AbstractCache<TKey, TValue, AccessExpireStrategy<TKey, TValue>, TMutex, TEventMutex>(AccessExpireStrategy<TKey, TValue>(expire)) + { + } + + ~AccessExpireCache() + { + } + +private: + AccessExpireCache(const AccessExpireCache& aCache); + AccessExpireCache& operator = (const AccessExpireCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_AccessExpireCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AccessExpireLRUCache.h b/contrib/libs/poco/Foundation/include/Poco/AccessExpireLRUCache.h new file mode 100644 index 0000000000..278cbbccd1 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AccessExpireLRUCache.h @@ -0,0 +1,62 @@ +// +// AccessExpireLRUCache.h +// +// Library: Foundation +// Package: Cache +// Module: AccessExpireLRUCache +// +// Definition of the AccessExpireLRUCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AccessExpireLRUCache_INCLUDED +#define Foundation_AccessExpireLRUCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/StrategyCollection.h" +#include "Poco/AccessExpireStrategy.h" +#include "Poco/LRUStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class AccessExpireLRUCache: public AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue>, TMutex, TEventMutex> + /// An AccessExpireLRUCache combines LRU caching and time based expire caching. + /// It cache entries for a fixed time period (per default 10 minutes) + /// but also limits the size of the cache (per default: 1024). +{ +public: + AccessExpireLRUCache(long cacheSize = 1024, Timestamp::TimeDiff expire = 600000): + AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue>, TMutex, TEventMutex >(StrategyCollection<TKey, TValue>()) + { + this->_strategy.pushBack(new LRUStrategy<TKey, TValue>(cacheSize)); + this->_strategy.pushBack(new AccessExpireStrategy<TKey, TValue>(expire)); + } + + ~AccessExpireLRUCache() + { + } + +private: + AccessExpireLRUCache(const AccessExpireLRUCache& aCache); + AccessExpireLRUCache& operator = (const AccessExpireLRUCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_AccessExpireLRUCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AccessExpireStrategy.h b/contrib/libs/poco/Foundation/include/Poco/AccessExpireStrategy.h new file mode 100644 index 0000000000..3bfa45c21f --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AccessExpireStrategy.h @@ -0,0 +1,74 @@ +// +// AccessExpireStrategy.h +// +// Library: Foundation +// Package: Cache +// Module: AccessExpireStrategy +// +// Definition of the AccessExpireStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AccessExpireStrategy_INCLUDED +#define Foundation_AccessExpireStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/ExpireStrategy.h" +#include "Poco/Bugcheck.h" +#include "Poco/Timestamp.h" +#include "Poco/EventArgs.h" +#include <set> +#include <map> + + +namespace Poco { + + +template < + class TKey, + class TValue +> +class AccessExpireStrategy: public ExpireStrategy<TKey, TValue> + /// An AccessExpireStrategy implements time and access based expiration of cache entries +{ +public: + AccessExpireStrategy(Timestamp::TimeDiff expireTimeInMilliSec): ExpireStrategy<TKey, TValue>(expireTimeInMilliSec) + /// Create an expire strategy. Note that the smallest allowed caching time is 25ms. + /// Anything lower than that is not useful with current operating systems. + { + } + + ~AccessExpireStrategy() + { + } + + void onGet(const void*, const TKey& key) + { + // get triggers an update to the expiration time + typename ExpireStrategy<TKey, TValue>::Iterator it = this->_keys.find(key); + if (it != this->_keys.end()) + { + if (!it->second->first.isElapsed(this->_expireTime)) // don't extend if already expired + { + this->_keyIndex.erase(it->second); + Timestamp now; + typename ExpireStrategy<TKey, TValue>::IndexIterator itIdx = + this->_keyIndex.insert(typename ExpireStrategy<TKey, TValue>::TimeIndex::value_type(now, key)); + it->second = itIdx; + } + } + } +}; + + +} // namespace Poco + + +#endif // Foundation_AccessExpireStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ActiveDispatcher.h b/contrib/libs/poco/Foundation/include/Poco/ActiveDispatcher.h new file mode 100644 index 0000000000..7550a2deae --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ActiveDispatcher.h @@ -0,0 +1,116 @@ +// +// ActiveDispatcher.h +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveDispatcher class. +// +// Copyright (c) 2006-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ActiveDispatcher_INCLUDED +#define Foundation_ActiveDispatcher_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/Thread.h" +#include "Poco/ActiveStarter.h" +#include "Poco/ActiveRunnable.h" +#include "Poco/NotificationQueue.h" + + +namespace Poco { + + +class Foundation_API ActiveDispatcher: protected Runnable + /// This class is used to implement an active object + /// with strictly serialized method execution. + /// + /// An active object, which is an ordinary object + /// containing ActiveMethod members, executes all + /// active methods in their own thread. + /// This behavior does not fit the "classic" + /// definition of an active object, which serializes + /// the execution of active methods (in other words, + /// only one active method can be running at any given + /// time). + /// + /// Using this class as a base class, the serializing + /// behavior for active objects can be implemented. + /// + /// The following example shows how this is done: + /// + /// class ActiveObject: public ActiveDispatcher + /// { + /// public: + /// ActiveObject(): + /// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl) + /// { + /// } + /// + /// ActiveMethod<std::string, std::string, ActiveObject, ActiveStarter<ActiveDispatcher> > exampleActiveMethod; + /// + /// protected: + /// std::string exampleActiveMethodImpl(const std::string& arg) + /// { + /// ... + /// } + /// }; + /// + /// The only things different from the example in + /// ActiveMethod is that the ActiveObject in this case + /// inherits from ActiveDispatcher, and that the ActiveMethod + /// template for exampleActiveMethod has an additional parameter, + /// specifying the specialized ActiveStarter for ActiveDispatcher. +{ +public: + ActiveDispatcher(); + /// Creates the ActiveDispatcher. + + ActiveDispatcher(Thread::Priority prio); + /// Creates the ActiveDispatcher and sets + /// the priority of its thread. + + virtual ~ActiveDispatcher(); + /// Destroys the ActiveDispatcher. + + void start(ActiveRunnableBase::Ptr pRunnable); + /// Adds the Runnable to the dispatch queue. + + void cancel(); + /// Cancels all queued methods. + +protected: + void run(); + void stop(); + +private: + Thread _thread; + NotificationQueue _queue; +}; + + +template <> +class ActiveStarter<ActiveDispatcher> + /// A specialization of ActiveStarter + /// for ActiveDispatcher. +{ +public: + static void start(ActiveDispatcher* pOwner, ActiveRunnableBase::Ptr pRunnable) + { + pOwner->start(pRunnable); + } +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveDispatcher_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ActiveMethod.h b/contrib/libs/poco/Foundation/include/Poco/ActiveMethod.h new file mode 100644 index 0000000000..cefd8f76dc --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ActiveMethod.h @@ -0,0 +1,218 @@ +// +// ActiveMethod.h +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveMethod class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ActiveMethod_INCLUDED +#define Foundation_ActiveMethod_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ActiveResult.h" +#include "Poco/ActiveRunnable.h" +#include "Poco/ActiveStarter.h" +#include "Poco/AutoPtr.h" + + +namespace Poco { + + +template <class ResultType, class ArgType, class OwnerType, class StarterType = ActiveStarter<OwnerType> > +class ActiveMethod + /// An active method is a method that, when called, executes + /// in its own thread. ActiveMethod's take exactly one + /// argument and can return a value. To pass more than one + /// argument to the method, use a struct. + /// The following example shows how to add an ActiveMethod + /// to a class: + /// + /// class ActiveObject + /// { + /// public: + /// ActiveObject(): + /// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl) + /// { + /// } + /// + /// ActiveMethod<std::string, std::string, ActiveObject> exampleActiveMethod; + /// + /// protected: + /// std::string exampleActiveMethodImpl(const std::string& arg) + /// { + /// ... + /// } + /// }; + /// + /// And following is an example that shows how to invoke an ActiveMethod. + /// + /// ActiveObject myActiveObject; + /// ActiveResult<std::string> result = myActiveObject.exampleActiveMethod("foo"); + /// ... + /// result.wait(); + /// std::cout << result.data() << std::endl; + /// + /// The way an ActiveMethod is started can be changed by passing a StarterType + /// template argument with a corresponding class. The default ActiveStarter + /// starts the method in its own thread, obtained from a thread pool. + /// + /// For an alternative implementation of StarterType, see ActiveDispatcher. + /// + /// For methods that do not require an argument or a return value, the Void + /// class can be used. +{ +public: + typedef ResultType (OwnerType::*Callback)(const ArgType&); + typedef ActiveResult<ResultType> ActiveResultType; + typedef ActiveRunnable<ResultType, ArgType, OwnerType> ActiveRunnableType; + + ActiveMethod(OwnerType* pOwner, Callback method): + _pOwner(pOwner), + _method(method) + /// Creates an ActiveMethod object. + { + poco_check_ptr (pOwner); + } + + ActiveResultType operator () (const ArgType& arg) + /// Invokes the ActiveMethod. + { + ActiveResultType result(new ActiveResultHolder<ResultType>()); + ActiveRunnableBase::Ptr pRunnable(new ActiveRunnableType(_pOwner, _method, arg, result)); + StarterType::start(_pOwner, pRunnable); + return result; + } + + ActiveMethod(const ActiveMethod& other): + _pOwner(other._pOwner), + _method(other._method) + { + } + + ActiveMethod& operator = (const ActiveMethod& other) + { + ActiveMethod tmp(other); + swap(tmp); + return *this; + } + + void swap(ActiveMethod& other) + { + std::swap(_pOwner, other._pOwner); + std::swap(_method, other._method); + } + +private: + ActiveMethod(); + + OwnerType* _pOwner; + Callback _method; +}; + + + +template <class ResultType, class OwnerType, class StarterType> +class ActiveMethod <ResultType, void, OwnerType, StarterType> + /// An active method is a method that, when called, executes + /// in its own thread. ActiveMethod's take exactly one + /// argument and can return a value. To pass more than one + /// argument to the method, use a struct. + /// The following example shows how to add an ActiveMethod + /// to a class: + /// + /// class ActiveObject + /// { + /// public: + /// ActiveObject(): + /// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl) + /// { + /// } + /// + /// ActiveMethod<std::string, std::string, ActiveObject> exampleActiveMethod; + /// + /// protected: + /// std::string exampleActiveMethodImpl(const std::string& arg) + /// { + /// ... + /// } + /// }; + /// + /// And following is an example that shows how to invoke an ActiveMethod. + /// + /// ActiveObject myActiveObject; + /// ActiveResult<std::string> result = myActiveObject.exampleActiveMethod("foo"); + /// ... + /// result.wait(); + /// std::cout << result.data() << std::endl; + /// + /// The way an ActiveMethod is started can be changed by passing a StarterType + /// template argument with a corresponding class. The default ActiveStarter + /// starts the method in its own thread, obtained from a thread pool. + /// + /// For an alternative implementation of StarterType, see ActiveDispatcher. + /// + /// For methods that do not require an argument or a return value, simply use void. +{ +public: + typedef ResultType (OwnerType::*Callback)(void); + typedef ActiveResult<ResultType> ActiveResultType; + typedef ActiveRunnable<ResultType, void, OwnerType> ActiveRunnableType; + + ActiveMethod(OwnerType* pOwner, Callback method): + _pOwner(pOwner), + _method(method) + /// Creates an ActiveMethod object. + { + poco_check_ptr (pOwner); + } + + ActiveResultType operator () (void) + /// Invokes the ActiveMethod. + { + ActiveResultType result(new ActiveResultHolder<ResultType>()); + ActiveRunnableBase::Ptr pRunnable(new ActiveRunnableType(_pOwner, _method, result)); + StarterType::start(_pOwner, pRunnable); + return result; + } + + ActiveMethod(const ActiveMethod& other): + _pOwner(other._pOwner), + _method(other._method) + { + } + + ActiveMethod& operator = (const ActiveMethod& other) + { + ActiveMethod tmp(other); + swap(tmp); + return *this; + } + + void swap(ActiveMethod& other) + { + std::swap(_pOwner, other._pOwner); + std::swap(_method, other._method); + } + +private: + ActiveMethod(); + + OwnerType* _pOwner; + Callback _method; +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveMethod_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ActiveResult.h b/contrib/libs/poco/Foundation/include/Poco/ActiveResult.h new file mode 100644 index 0000000000..4cdc0ed0bf --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ActiveResult.h @@ -0,0 +1,495 @@ +// +// ActiveResult.h +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveResult class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ActiveResult_INCLUDED +#define Foundation_ActiveResult_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" +#include "Poco/RefCountedObject.h" +#include "Poco/Exception.h" +#include <algorithm> + + +namespace Poco { + + +template <class ResultType> +class ActiveResultHolder: public RefCountedObject + /// This class holds the result of an asynchronous method + /// invocation. It is used to pass the result from the + /// execution thread back to the invocation thread. + /// The class uses reference counting for memory management. + /// Do not use this class directly, use ActiveResult instead. +{ +public: + ActiveResultHolder(): + _pData(0), + _pExc(0), + _event(false) + /// Creates an ActiveResultHolder. + { + } + + ResultType& data() + /// Returns a reference to the actual result. + { + poco_check_ptr(_pData); + return *_pData; + } + + void data(ResultType* pData) + { + delete _pData; + _pData = pData; + } + + void wait() + /// Pauses the caller until the result becomes available. + { + _event.wait(); + } + + bool tryWait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Returns true if the result became + /// available, false otherwise. + { + return _event.tryWait(milliseconds); + } + + void wait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Throws a TimeoutException if the + /// result did not became available. + { + _event.wait(milliseconds); + } + + void notify() + /// Notifies the invoking thread that the result became available. + { + _event.set(); + } + + bool failed() const + /// Returns true if the active method failed (and threw an exception). + /// Information about the exception can be obtained by calling error(). + { + return _pExc != 0; + } + + std::string error() const + /// If the active method threw an exception, a textual representation + /// of the exception is returned. An empty string is returned if the + /// active method completed successfully. + { + if (_pExc) + return _pExc->message(); + else + return std::string(); + } + + Exception* exception() const + /// If the active method threw an exception, a clone of the exception + /// object is returned, otherwise null. + { + return _pExc; + } + + void error(const Exception& exc) + /// Sets the exception. + { + delete _pExc; + _pExc = exc.clone(); + } + + void error(const std::string& msg) + /// Sets the exception. + { + delete _pExc; + _pExc = new UnhandledException(msg); + } + +protected: + ~ActiveResultHolder() + { + delete _pData; + delete _pExc; + } + +private: + ResultType* _pData; + Exception* _pExc; + Event _event; +}; + + + +template <> +class ActiveResultHolder<void>: public RefCountedObject +{ +public: + ActiveResultHolder(): + _pExc(0), + _event(false) + /// Creates an ActiveResultHolder. + { + } + + void wait() + /// Pauses the caller until the result becomes available. + { + _event.wait(); + } + + bool tryWait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Returns true if the result became + /// available, false otherwise. + { + return _event.tryWait(milliseconds); + } + + void wait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Throws a TimeoutException if the + /// result did not became available. + { + _event.wait(milliseconds); + } + + void notify() + /// Notifies the invoking thread that the result became available. + { + _event.set(); + } + + bool failed() const + /// Returns true if the active method failed (and threw an exception). + /// Information about the exception can be obtained by calling error(). + { + return _pExc != 0; + } + + std::string error() const + /// If the active method threw an exception, a textual representation + /// of the exception is returned. An empty string is returned if the + /// active method completed successfully. + { + if (_pExc) + return _pExc->message(); + else + return std::string(); + } + + Exception* exception() const + /// If the active method threw an exception, a clone of the exception + /// object is returned, otherwise null. + { + return _pExc; + } + + void error(const Exception& exc) + /// Sets the exception. + { + delete _pExc; + _pExc = exc.clone(); + } + + void error(const std::string& msg) + /// Sets the exception. + { + delete _pExc; + _pExc = new UnhandledException(msg); + } + +protected: + ~ActiveResultHolder() + { + delete _pExc; + } + +private: + Exception* _pExc; + Event _event; +}; + + +template <class RT> +class ActiveResult + /// This class holds the result of an asynchronous method + /// invocation (see class ActiveMethod). It is used to pass the + /// result from the execution thread back to the invocation thread. +{ +public: + typedef RT ResultType; + typedef ActiveResultHolder<ResultType> ActiveResultHolderType; + + ActiveResult(ActiveResultHolderType* pHolder): + _pHolder(pHolder) + /// Creates the active result. For internal use only. + { + poco_check_ptr (pHolder); + } + + ActiveResult(const ActiveResult& result) + /// Copy constructor. + { + _pHolder = result._pHolder; + _pHolder->duplicate(); + } + + ~ActiveResult() + /// Destroys the result. + { + _pHolder->release(); + } + + ActiveResult& operator = (const ActiveResult& result) + /// Assignment operator. + { + ActiveResult tmp(result); + swap(tmp); + return *this; + } + + void swap(ActiveResult& result) + { + using std::swap; + swap(_pHolder, result._pHolder); + } + + ResultType& data() const + /// Returns a reference to the result data. + { + return _pHolder->data(); + } + + void data(ResultType* pValue) + { + _pHolder->data(pValue); + } + + void wait() + /// Pauses the caller until the result becomes available. + { + _pHolder->wait(); + } + + bool tryWait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Returns true if the result became + /// available, false otherwise. + { + return _pHolder->tryWait(milliseconds); + } + + void wait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Throws a TimeoutException if the + /// result did not became available. + { + _pHolder->wait(milliseconds); + } + + bool available() const + /// Returns true if a result is available. + { + return _pHolder->tryWait(0); + } + + bool failed() const + /// Returns true if the active method failed (and threw an exception). + /// Information about the exception can be obtained by calling error(). + { + return _pHolder->failed(); + } + + std::string error() const + /// If the active method threw an exception, a textual representation + /// of the exception is returned. An empty string is returned if the + /// active method completed successfully. + { + return _pHolder->error(); + } + + Exception* exception() const + /// If the active method threw an exception, a clone of the exception + /// object is returned, otherwise null. + { + return _pHolder->exception(); + } + + void notify() + /// Notifies the invoking thread that the result became available. + /// For internal use only. + { + _pHolder->notify(); + } + + ResultType& data() + /// Returns a non-const reference to the result data. For internal + /// use only. + { + return _pHolder->data(); + } + + void error(const std::string& msg) + /// Sets the failed flag and the exception message. + { + _pHolder->error(msg); + } + + void error(const Exception& exc) + /// Sets the failed flag and the exception message. + { + _pHolder->error(exc); + } + +private: + ActiveResult(); + + ActiveResultHolderType* _pHolder; +}; + + + +template <> +class ActiveResult<void> + /// This class holds the result of an asynchronous method + /// invocation (see class ActiveMethod). It is used to pass the + /// result from the execution thread back to the invocation thread. +{ +public: + typedef ActiveResultHolder<void> ActiveResultHolderType; + + ActiveResult(ActiveResultHolderType* pHolder): + _pHolder(pHolder) + /// Creates the active result. For internal use only. + { + poco_check_ptr (pHolder); + } + + ActiveResult(const ActiveResult& result) + /// Copy constructor. + { + _pHolder = result._pHolder; + _pHolder->duplicate(); + } + + ~ActiveResult() + /// Destroys the result. + { + _pHolder->release(); + } + + ActiveResult& operator = (const ActiveResult& result) + /// Assignment operator. + { + ActiveResult tmp(result); + swap(tmp); + return *this; + } + + void swap(ActiveResult& result) + { + using std::swap; + swap(_pHolder, result._pHolder); + } + + void wait() + /// Pauses the caller until the result becomes available. + { + _pHolder->wait(); + } + + bool tryWait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Returns true if the result became + /// available, false otherwise. + { + return _pHolder->tryWait(milliseconds); + } + + void wait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Throws a TimeoutException if the + /// result did not became available. + { + _pHolder->wait(milliseconds); + } + + bool available() const + /// Returns true if a result is available. + { + return _pHolder->tryWait(0); + } + + bool failed() const + /// Returns true if the active method failed (and threw an exception). + /// Information about the exception can be obtained by calling error(). + { + return _pHolder->failed(); + } + + std::string error() const + /// If the active method threw an exception, a textual representation + /// of the exception is returned. An empty string is returned if the + /// active method completed successfully. + { + return _pHolder->error(); + } + + Exception* exception() const + /// If the active method threw an exception, a clone of the exception + /// object is returned, otherwise null. + { + return _pHolder->exception(); + } + + void notify() + /// Notifies the invoking thread that the result became available. + /// For internal use only. + { + _pHolder->notify(); + } + + void error(const std::string& msg) + /// Sets the failed flag and the exception message. + { + _pHolder->error(msg); + } + + void error(const Exception& exc) + /// Sets the failed flag and the exception message. + { + _pHolder->error(exc); + } + +private: + ActiveResult(); + + ActiveResultHolderType* _pHolder; +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveResult_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ActiveRunnable.h b/contrib/libs/poco/Foundation/include/Poco/ActiveRunnable.h new file mode 100644 index 0000000000..95317b0b3f --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ActiveRunnable.h @@ -0,0 +1,231 @@ +// +// ActiveRunnable.h +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveRunnable class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ActiveRunnable_INCLUDED +#define Foundation_ActiveRunnable_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ActiveResult.h" +#include "Poco/Runnable.h" +#include "Poco/RefCountedObject.h" +#include "Poco/AutoPtr.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +class ActiveRunnableBase: public Runnable, public RefCountedObject + /// The base class for all ActiveRunnable instantiations. +{ +public: + typedef AutoPtr<ActiveRunnableBase> Ptr; +}; + + +template <class ResultType, class ArgType, class OwnerType> +class ActiveRunnable: public ActiveRunnableBase + /// This class is used by ActiveMethod. + /// See the ActiveMethod class for more information. +{ +public: + typedef ResultType (OwnerType::*Callback)(const ArgType&); + typedef ActiveResult<ResultType> ActiveResultType; + + ActiveRunnable(OwnerType* pOwner, Callback method, const ArgType& arg, const ActiveResultType& result): + _pOwner(pOwner), + _method(method), + _arg(arg), + _result(result) + { + poco_check_ptr (pOwner); + } + + void run() + { + ActiveRunnableBase::Ptr guard(this, false); // ensure automatic release when done + try + { + _result.data(new ResultType((_pOwner->*_method)(_arg))); + } + catch (Exception& e) + { + _result.error(e); + } + catch (std::exception& e) + { + _result.error(e.what()); + } + catch (...) + { + _result.error("unknown exception"); + } + _result.notify(); + } + +private: + OwnerType* _pOwner; + Callback _method; + ArgType _arg; + ActiveResultType _result; +}; + + +template <class ArgType, class OwnerType> +class ActiveRunnable<void, ArgType, OwnerType>: public ActiveRunnableBase + /// This class is used by ActiveMethod. + /// See the ActiveMethod class for more information. +{ +public: + typedef void (OwnerType::*Callback)(const ArgType&); + typedef ActiveResult<void> ActiveResultType; + + ActiveRunnable(OwnerType* pOwner, Callback method, const ArgType& arg, const ActiveResultType& result): + _pOwner(pOwner), + _method(method), + _arg(arg), + _result(result) + { + poco_check_ptr (pOwner); + } + + void run() + { + ActiveRunnableBase::Ptr guard(this, false); // ensure automatic release when done + try + { + (_pOwner->*_method)(_arg); + } + catch (Exception& e) + { + _result.error(e); + } + catch (std::exception& e) + { + _result.error(e.what()); + } + catch (...) + { + _result.error("unknown exception"); + } + _result.notify(); + } + +private: + OwnerType* _pOwner; + Callback _method; + ArgType _arg; + ActiveResultType _result; +}; + + +template <class ResultType, class OwnerType> +class ActiveRunnable<ResultType, void, OwnerType>: public ActiveRunnableBase + /// This class is used by ActiveMethod. + /// See the ActiveMethod class for more information. +{ +public: + typedef ResultType (OwnerType::*Callback)(); + typedef ActiveResult<ResultType> ActiveResultType; + + ActiveRunnable(OwnerType* pOwner, Callback method, const ActiveResultType& result): + _pOwner(pOwner), + _method(method), + _result(result) + { + poco_check_ptr (pOwner); + } + + void run() + { + ActiveRunnableBase::Ptr guard(this, false); // ensure automatic release when done + try + { + _result.data(new ResultType((_pOwner->*_method)())); + } + catch (Exception& e) + { + _result.error(e); + } + catch (std::exception& e) + { + _result.error(e.what()); + } + catch (...) + { + _result.error("unknown exception"); + } + _result.notify(); + } + +private: + OwnerType* _pOwner; + Callback _method; + ActiveResultType _result; +}; + + +template <class OwnerType> +class ActiveRunnable<void, void, OwnerType>: public ActiveRunnableBase + /// This class is used by ActiveMethod. + /// See the ActiveMethod class for more information. +{ +public: + typedef void (OwnerType::*Callback)(); + typedef ActiveResult<void> ActiveResultType; + + ActiveRunnable(OwnerType* pOwner, Callback method, const ActiveResultType& result): + _pOwner(pOwner), + _method(method), + _result(result) + { + poco_check_ptr (pOwner); + } + + void run() + { + ActiveRunnableBase::Ptr guard(this, false); // ensure automatic release when done + try + { + (_pOwner->*_method)(); + } + catch (Exception& e) + { + _result.error(e); + } + catch (std::exception& e) + { + _result.error(e.what()); + } + catch (...) + { + _result.error("unknown exception"); + } + _result.notify(); + } + +private: + OwnerType* _pOwner; + Callback _method; + ActiveResultType _result; +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveRunnable_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ActiveStarter.h b/contrib/libs/poco/Foundation/include/Poco/ActiveStarter.h new file mode 100644 index 0000000000..b79a31e8f8 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ActiveStarter.h @@ -0,0 +1,48 @@ +// +// ActiveStarter.h +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveStarter class. +// +// Copyright (c) 2006-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ActiveStarter_INCLUDED +#define Foundation_ActiveStarter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ThreadPool.h" +#include "Poco/ActiveRunnable.h" + + +namespace Poco { + + +template <class OwnerType> +class ActiveStarter + /// The default implementation of the StarterType + /// policy for ActiveMethod. It starts the method + /// in its own thread, obtained from the default + /// thread pool. +{ +public: + static void start(OwnerType* /*pOwner*/, ActiveRunnableBase::Ptr pRunnable) + { + ThreadPool::defaultPool().start(*pRunnable); + pRunnable->duplicate(); // The runnable will release itself. + } +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveStarter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Activity.h b/contrib/libs/poco/Foundation/include/Poco/Activity.h new file mode 100644 index 0000000000..a7297f144f --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Activity.h @@ -0,0 +1,208 @@ +// +// Activity.h +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the Activity template class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Activity_INCLUDED +#define Foundation_Activity_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RunnableAdapter.h" +#include "Poco/ThreadPool.h" +#include "Poco/Event.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class C> +class Activity: public Runnable + /// This template class helps to implement active objects. + /// An active object uses threads to decouple method + /// execution from method invocation, or to perform tasks + /// autonomously, without intervention of a caller. + /// + /// An activity is a (typically longer running) method + /// that executes within its own task. Activities can + /// be started automatically (upon object construction) + /// or manually at a later time. Activities can also + /// be stopped at any time. However, to make stopping + /// an activity work, the method implementing the + /// activity has to check periodically whether it + /// has been requested to stop, and if so, return. + /// Activities are stopped before the object they belong to is + /// destroyed. Methods implementing activities cannot have arguments + /// or return values. + /// + /// Activity objects are used as follows: + /// + /// class ActiveObject + /// { + /// public: + /// ActiveObject(): + /// _activity(this, &ActiveObject::runActivity) + /// { + /// ... + /// } + /// + /// ... + /// + /// protected: + /// void runActivity() + /// { + /// while (!_activity.isStopped()) + /// { + /// ... + /// } + /// } + /// + /// private: + /// Activity<ActiveObject> _activity; + /// }; +{ +public: + typedef RunnableAdapter<C> RunnableAdapterType; + typedef typename RunnableAdapterType::Callback Callback; + + Activity(C* pOwner, Callback method): + _pOwner(pOwner), + _runnable(*pOwner, method), + _stopped(true), + _running(false), + _done(false) + /// Creates the activity. Call start() to + /// start it. + { + poco_check_ptr (pOwner); + } + + ~Activity() + /// Stops and destroys the activity. + { + try + { + stop(); + wait(); + } + catch (...) + { + poco_unexpected(); + } + } + + void start() + /// Starts the activity by acquiring a + /// thread for it from the default thread pool. + { + start(ThreadPool::defaultPool()); + } + + void start(ThreadPool& pool) + { + FastMutex::ScopedLock lock(_mutex); + + if (!_running) + { + _done.reset(); + _stopped = false; + _running = true; + try + { + pool.start(*this); + } + catch (...) + { + _running = false; + throw; + } + } + } + + void stop() + /// Requests to stop the activity. + { + FastMutex::ScopedLock lock(_mutex); + + _stopped = true; + } + + void wait() + /// Waits for the activity to complete. + { + if (_running) + { + _done.wait(); + } + } + + void wait(long milliseconds) + /// Waits the given interval for the activity to complete. + /// An TimeoutException is thrown if the activity does not + /// complete within the given interval. + { + if (_running) + { + _done.wait(milliseconds); + } + } + + bool isStopped() const + /// Returns true if the activity has been requested to stop. + { + return _stopped; + } + + bool isRunning() const + /// Returns true if the activity is running. + { + return _running; + } + +protected: + void run() + { + try + { + _runnable.run(); + } + catch (...) + { + _running = false; + _done.set(); + throw; + } + _running = false; + _done.set(); + } + +private: + Activity(); + Activity(const Activity&); + Activity& operator = (const Activity&); + + C* _pOwner; + RunnableAdapterType _runnable; + volatile bool _stopped; + volatile bool _running; + Event _done; + FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_Activity_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Alignment.h b/contrib/libs/poco/Foundation/include/Poco/Alignment.h new file mode 100644 index 0000000000..d655a3d9f4 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Alignment.h @@ -0,0 +1,246 @@ +// +// Alignment.h +// +// Library: Foundation +// Package: Dynamic +// Module: Alignment +// +// Definition of the Alignment class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +// Adapted for POCO from LLVM Compiler Infrastructure code: +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source License +// +//===----------------------------------------------------------------------===// +// +// This file defines the AlignOf function that computes alignments for +// arbitrary types. +// +//===----------------------------------------------------------------------===// + + +#ifndef Foundation_AlignOf_INCLUDED +#define Foundation_AlignOf_INCLUDED + + +#include <cstddef> + + +#ifdef POCO_ENABLE_CPP11 + + + #include <type_traits> + #define POCO_HAVE_ALIGNMENT + + +#else + + + namespace Poco { + + + template <typename T> + struct AlignmentCalcImpl + { + char x; + T t; + private: + AlignmentCalcImpl() {} // Never instantiate. + }; + + + template <typename T> + struct AlignOf + /// A templated class that contains an enum value representing + /// the alignment of the template argument. For example, + /// AlignOf<int>::Alignment represents the alignment of type "int". The + /// alignment calculated is the minimum alignment, and not necessarily + /// the "desired" alignment returned by GCC's __alignof__ (for example). Note + /// that because the alignment is an enum value, it can be used as a + /// compile-time constant (e.g., for template instantiation). + { + enum + { + Alignment = static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T)) + }; + + enum { Alignment_GreaterEqual_2Bytes = Alignment >= 2 ? 1 : 0 }; + enum { Alignment_GreaterEqual_4Bytes = Alignment >= 4 ? 1 : 0 }; + enum { Alignment_GreaterEqual_8Bytes = Alignment >= 8 ? 1 : 0 }; + enum { Alignment_GreaterEqual_16Bytes = Alignment >= 16 ? 1 : 0 }; + + enum { Alignment_LessEqual_2Bytes = Alignment <= 2 ? 1 : 0 }; + enum { Alignment_LessEqual_4Bytes = Alignment <= 4 ? 1 : 0 }; + enum { Alignment_LessEqual_8Bytes = Alignment <= 8 ? 1 : 0 }; + enum { Alignment_LessEqual_16Bytes = Alignment <= 16 ? 1 : 0 }; + + }; + + + template <typename T> + inline unsigned alignOf() + /// A templated function that returns the minimum alignment of + /// of a type. This provides no extra functionality beyond the AlignOf + /// class besides some cosmetic cleanliness. Example usage: + /// alignOf<int>() returns the alignment of an int. + { + return AlignOf<T>::Alignment; + } + + + template <std::size_t Alignment> struct AlignedCharArrayImpl; + /// Helper for building an aligned character array type. + /// + /// This template is used to explicitly build up a collection of aligned + /// character types. We have to build these up using a macro and explicit + /// specialization to cope with old versions of MSVC and GCC where only an + /// integer literal can be used to specify an alignment constraint. Once built + /// up here, we can then begin to indirect between these using normal C++ + /// template parameters. + + + // MSVC requires special handling here. + #ifndef _MSC_VER + + #ifdef POCO_COMPILER_CLANG + + #if __has_feature(cxx_alignas) + #define POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \ + template <> struct AlignedCharArrayImpl<x> \ + { \ + char aligned alignas(x); \ + } + #define POCO_HAVE_ALIGNMENT + #endif + + #elif defined(__GNUC__) || defined(__IBM_ATTRIBUTES) + + #define POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \ + template <> struct AlignedCharArrayImpl<x> \ + { \ + char aligned __attribute__((aligned(x))); \ + } + #define POCO_HAVE_ALIGNMENT + + #endif + + #ifdef POCO_HAVE_ALIGNMENT + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(512); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1024); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2048); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4096); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8192); + + #undef POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT + #endif // POCO_HAVE_ALIGNMENT + + #else // _MSC_VER + + // We provide special variations of this template for the most common + // alignments because __declspec(align(...)) doesn't actually work when it is + // a member of a by-value function argument in MSVC, even if the alignment + // request is something reasonably like 8-byte or 16-byte. + template <> struct AlignedCharArrayImpl<1> { char aligned; }; + template <> struct AlignedCharArrayImpl<2> { short aligned; }; + template <> struct AlignedCharArrayImpl<4> { int aligned; }; + template <> struct AlignedCharArrayImpl<8> { double aligned; }; + + #define POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \ + template <> struct AlignedCharArrayImpl<x> { \ + __declspec(align(x)) char aligned; \ + } + + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128); + + #if (_MSC_VER > 1600) // MSVC 2010 complains on alignment larger than 128 + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(512); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1024); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2048); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4096); + POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8192); + #endif // _MSC_VER > 1600 + + // Any larger and MSVC complains. + #undef POCO_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT + + #define POCO_HAVE_ALIGNMENT + #endif // _MSC_VER + + // POCO_HAVE_ALIGNMENT will be defined on the pre-C++11 platforms/compilers where + // it can be reliably determined and used. Uncomment the line below to explicitly + // disable use of alignment even for those platforms. + // #undef POCO_HAVE_ALIGNMENT + + + #ifdef POCO_HAVE_ALIGNMENT + + template <typename T1, typename T2 = char, typename T3 = char, typename T4 = char> + union AlignedCharArrayUnion + /// This union template exposes a suitably aligned and sized character + /// array member which can hold elements of any of up to four types. + /// + /// These types may be arrays, structs, or any other types. The goal is to + /// produce a union type containing a character array which, when used, forms + /// storage suitable to placement new any of these types over. Support for more + /// than four types can be added at the cost of more boiler plate. + { + private: + class AlignerImpl + { + T1 t1; + T2 t2; + T3 t3; + T4 t4; + + AlignerImpl(); // Never defined or instantiated. + }; + + union SizerImpl + { + char arr1[sizeof(T1)]; + char arr2[sizeof(T2)]; + char arr3[sizeof(T3)]; + char arr4[sizeof(T4)]; + }; + + public: + char buffer[sizeof(SizerImpl)]; + /// The character array buffer for use by clients. + /// + /// No other member of this union should be referenced. They exist purely to + /// constrain the layout of this character array. + + private: + Poco::AlignedCharArrayImpl<AlignOf<AlignerImpl>::Alignment> _nonceMember; + + }; + + #endif // POCO_HAVE_ALIGNMENT + + } // namespace Poco + + +#endif // POCO_ENABLE_CPP11 + + +#endif // Foundation_AlignOf_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Any.h b/contrib/libs/poco/Foundation/include/Poco/Any.h new file mode 100644 index 0000000000..30f5b76417 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Any.h @@ -0,0 +1,599 @@ +// +// Any.h +// +// Library: Foundation +// Package: Core +// Module: Any +// +// Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. +// Extracted from Boost 1.33.1 lib and adapted for poco: Peter Schojer/AppliedInformatics 2006-02-02 +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Any_INCLUDED +#define Foundation_Any_INCLUDED + + +#include "Poco/Exception.h" +#include "Poco/MetaProgramming.h" +#include <algorithm> +#include <typeinfo> +#include <cstring> + + +namespace Poco { + + +class Any; + + +namespace Dynamic { + +class Var; +class VarHolder; +template <class> class VarHolderImpl; + +} + +#ifndef POCO_NO_SOO + +#ifndef POCO_ENABLE_CPP11 + // C++11 needed for std::aligned_storage + #error "Any SOO can only be enabled with C++11 support" +#endif + +template <typename PlaceholderT, unsigned int SizeV = POCO_SMALL_OBJECT_SIZE> +union Placeholder + /// ValueHolder union (used by Poco::Any and Poco::Dynamic::Var for small + /// object optimization, when enabled). + /// + /// If Holder<Type> fits into POCO_SMALL_OBJECT_SIZE bytes of storage, + /// it will be placement-new-allocated into the local buffer + /// (i.e. there will be no heap-allocation). The local buffer size is one byte + /// larger - [POCO_SMALL_OBJECT_SIZE + 1], additional byte value indicating + /// where the object was allocated (0 => heap, 1 => local). +{ +public: + struct Size + { + static const unsigned int value = SizeV; + }; + + Placeholder () + { + erase(); + } + + void erase() + { + std::memset(holder, 0, sizeof(Placeholder)); + } + + bool isLocal() const + { + return holder[SizeV] != 0; + } + + void setLocal(bool local) const + { + holder[SizeV] = local ? 1 : 0; + } + + PlaceholderT* content() const + { + if (isLocal()) + return reinterpret_cast<PlaceholderT*>(holder); + else + return pHolder; + } + +// MSVC71,80 won't extend friendship to nested class (Any::Holder) +#if !defined(POCO_MSVC_VERSION) || (defined(POCO_MSVC_VERSION) && (POCO_MSVC_VERSION > 80)) +private: +#endif + typedef typename std::aligned_storage<SizeV + 1>::type AlignerType; + + PlaceholderT* pHolder; + mutable char holder [SizeV + 1]; + AlignerType aligner; + + friend class Any; + friend class Dynamic::Var; + friend class Dynamic::VarHolder; + template <class> friend class Dynamic::VarHolderImpl; +}; + + +#else // !POCO_NO_SOO + + +template <typename PlaceholderT> +union Placeholder + /// ValueHolder union (used by Poco::Any and Poco::Dynamic::Var for small + /// object optimization, when enabled). + /// + /// If Holder<Type> fits into POCO_SMALL_OBJECT_SIZE bytes of storage, + /// it will be placement-new-allocated into the local buffer + /// (i.e. there will be no heap-allocation). The local buffer size is one byte + /// larger - [POCO_SMALL_OBJECT_SIZE + 1], additional byte value indicating + /// where the object was allocated (0 => heap, 1 => local). +{ +public: + + Placeholder () + { + } + + PlaceholderT* content() const + { + return pHolder; + } + +// MSVC71,80 won't extend friendship to nested class (Any::Holder) +#if !defined(POCO_MSVC_VERSION) || (defined(POCO_MSVC_VERSION) && (POCO_MSVC_VERSION > 80)) +private: +#endif + + PlaceholderT* pHolder; + + friend class Any; + friend class Dynamic::Var; + friend class Dynamic::VarHolder; + template <class> friend class Dynamic::VarHolderImpl; +}; + + +#endif // POCO_NO_SOO + + +class Any + /// An Any class represents a general type and is capable of storing any type, supporting type-safe extraction + /// of the internally stored data. + /// + /// Code taken from the Boost 1.33.1 library. Original copyright by Kevlin Henney. Modified for Poco + /// by Applied Informatics. + /// + /// Modified for small object optimization support (optionally supported through conditional compilation) + /// by Alex Fabijanic. +{ +public: + +#ifndef POCO_NO_SOO + + Any() + /// Creates an empty any type. + { + } + + template<typename ValueType> + Any(const ValueType & value) + /// Creates an any which stores the init parameter inside. + /// + /// Example: + /// Any a(13); + /// Any a(string("12345")); + { + construct(value); + } + + Any(const Any& other) + /// Copy constructor, works with both empty and initialized Any values. + { + if ((this != &other) && !other.empty()) + construct(other); + } + + ~Any() + /// Destructor. If Any is locally held, calls ValueHolder destructor; + /// otherwise, deletes the placeholder from the heap. + { + if (!empty()) + { + if (_valueHolder.isLocal()) + destruct(); + else + delete content(); + } + } + + Any& swap(Any& other) + /// Swaps the content of the two Anys. + /// + /// When small object optimizaton is enabled, swap only + /// has no-throw guarantee when both (*this and other) + /// objects are allocated on the heap. + { + if (this == &other) return *this; + + if (!_valueHolder.isLocal() && !other._valueHolder.isLocal()) + { + std::swap(_valueHolder.pHolder, other._valueHolder.pHolder); + } + else + { + Any tmp(*this); + try + { + if (_valueHolder.isLocal()) destruct(); + construct(other); + other = tmp; + } + catch (...) + { + construct(tmp); + throw; + } + } + + return *this; + } + + template<typename ValueType> + Any& operator = (const ValueType& rhs) + /// Assignment operator for all types != Any. + /// + /// Example: + /// Any a = 13; + /// Any a = string("12345"); + { + construct(rhs); + return *this; + } + + Any& operator = (const Any& rhs) + /// Assignment operator for Any. + { + if ((this != &rhs) && !rhs.empty()) + construct(rhs); + else if ((this != &rhs) && rhs.empty()) + _valueHolder.erase(); + + return *this; + } + + bool empty() const + /// Returns true if the Any is empty. + { + char buf[POCO_SMALL_OBJECT_SIZE] = { 0 }; + return 0 == std::memcmp(_valueHolder.holder, buf, POCO_SMALL_OBJECT_SIZE); + } + + const std::type_info & type() const + /// Returns the type information of the stored content. + /// If the Any is empty typeid(void) is returned. + /// It is recommended to always query an Any for its type info before + /// trying to extract data via an AnyCast/RefAnyCast. + { + return empty() ? typeid(void) : content()->type(); + } + +private: + + class ValueHolder + { + public: + + virtual ~ValueHolder() + { + } + + virtual const std::type_info & type() const = 0; + virtual void clone(Placeholder<ValueHolder>*) const = 0; + }; + + template<typename ValueType> + class Holder : public ValueHolder + { + public: + Holder(const ValueType & value) : _held(value) + { + } + + virtual const std::type_info & type() const + { + return typeid(ValueType); + } + + virtual void clone(Placeholder<ValueHolder>* pPlaceholder) const + { + if ((sizeof(Holder<ValueType>) <= POCO_SMALL_OBJECT_SIZE)) + { + new ((ValueHolder*) pPlaceholder->holder) Holder(_held); + pPlaceholder->setLocal(true); + } + else + { + pPlaceholder->pHolder = new Holder(_held); + pPlaceholder->setLocal(false); + } + } + + ValueType _held; + + private: + Holder & operator = (const Holder &); + }; + + ValueHolder* content() const + { + return _valueHolder.content(); + } + + template<typename ValueType> + void construct(const ValueType& value) + { + if (sizeof(Holder<ValueType>) <= Placeholder<ValueType>::Size::value) + { + new (reinterpret_cast<ValueHolder*>(_valueHolder.holder)) Holder<ValueType>(value); + _valueHolder.setLocal(true); + } + else + { + _valueHolder.pHolder = new Holder<ValueType>(value); + _valueHolder.setLocal(false); + } + } + + void construct(const Any& other) + { + if (!other.empty()) + other.content()->clone(&_valueHolder); + else + _valueHolder.erase(); + } + + void destruct() + { + content()->~ValueHolder(); + } + + Placeholder<ValueHolder> _valueHolder; + + +#else // if POCO_NO_SOO + + + Any(): _pHolder(0) + /// Creates an empty any type. + { + } + + template <typename ValueType> + Any(const ValueType& value): + _pHolder(new Holder<ValueType>(value)) + /// Creates an any which stores the init parameter inside. + /// + /// Example: + /// Any a(13); + /// Any a(string("12345")); + { + } + + Any(const Any& other): + _pHolder(other._pHolder ? other._pHolder->clone() : 0) + /// Copy constructor, works with both empty and initialized Any values. + { + } + + ~Any() + { + delete _pHolder; + } + + Any& swap(Any& rhs) + /// Swaps the content of the two Anys. + { + std::swap(_pHolder, rhs._pHolder); + return *this; + } + + template <typename ValueType> + Any& operator = (const ValueType& rhs) + /// Assignment operator for all types != Any. + /// + /// Example: + /// Any a = 13; + /// Any a = string("12345"); + { + Any(rhs).swap(*this); + return *this; + } + + Any& operator = (const Any& rhs) + /// Assignment operator for Any. + { + Any(rhs).swap(*this); + return *this; + } + + bool empty() const + /// Returns true if the Any is empty. + { + return !_pHolder; + } + + const std::type_info& type() const + /// Returns the type information of the stored content. + /// If the Any is empty typeid(void) is returned. + /// It is recommended to always query an Any for its type info before + /// trying to extract data via an AnyCast/RefAnyCast. + { + return _pHolder ? _pHolder->type() : typeid(void); + } + +private: + class ValueHolder + { + public: + virtual ~ValueHolder() + { + } + + virtual const std::type_info& type() const = 0; + virtual ValueHolder* clone() const = 0; + }; + + template <typename ValueType> + class Holder: public ValueHolder + { + public: + Holder(const ValueType& value): + _held(value) + { + } + + virtual const std::type_info& type() const + { + return typeid(ValueType); + } + + virtual ValueHolder* clone() const + { + return new Holder(_held); + } + + ValueType _held; + + private: + Holder & operator=(const Holder &); + }; + + ValueHolder* content() const + { + return _pHolder; + } + +private: + ValueHolder* _pHolder; + +#endif // POCO_NO_SOO + + template <typename ValueType> + friend ValueType* AnyCast(Any*); + + template <typename ValueType> + friend ValueType* UnsafeAnyCast(Any*); + +}; + + +template <typename ValueType> +ValueType* AnyCast(Any* operand) + /// AnyCast operator used to extract the ValueType from an Any*. Will return a pointer + /// to the stored value. + /// + /// Example Usage: + /// MyType* pTmp = AnyCast<MyType*>(pAny). + /// Will return NULL if the cast fails, i.e. types don't match. +{ + return operand && operand->type() == typeid(ValueType) + ? &static_cast<Any::Holder<ValueType>*>(operand->content())->_held + : 0; +} + + +template <typename ValueType> +const ValueType* AnyCast(const Any* operand) + /// AnyCast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer + /// to the stored value. + /// + /// Example Usage: + /// const MyType* pTmp = AnyCast<MyType*>(pAny). + /// Will return NULL if the cast fails, i.e. types don't match. +{ + return AnyCast<ValueType>(const_cast<Any*>(operand)); +} + + +template <typename ValueType> +ValueType AnyCast(Any& operand) + /// AnyCast operator used to extract a copy of the ValueType from an Any&. + /// + /// Example Usage: + /// MyType tmp = AnyCast<MyType>(anAny). + /// Will throw a BadCastException if the cast fails. + /// Dont use an AnyCast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... + /// Some compilers will accept this code although a copy is returned. Use the RefAnyCast in + /// these cases. +{ + typedef typename TypeWrapper<ValueType>::TYPE NonRef; + + NonRef* result = AnyCast<NonRef>(&operand); + if (!result) throw BadCastException("Failed to convert between Any types"); + return *result; +} + + +template <typename ValueType> +ValueType AnyCast(const Any& operand) + /// AnyCast operator used to extract a copy of the ValueType from an const Any&. + /// + /// Example Usage: + /// MyType tmp = AnyCast<MyType>(anAny). + /// Will throw a BadCastException if the cast fails. + /// Dont use an AnyCast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... + /// Some compilers will accept this code although a copy is returned. Use the RefAnyCast in + /// these cases. +{ + typedef typename TypeWrapper<ValueType>::TYPE NonRef; + + return AnyCast<NonRef&>(const_cast<Any&>(operand)); +} + + +template <typename ValueType> +const ValueType& RefAnyCast(const Any & operand) + /// AnyCast operator used to return a const reference to the internal data. + /// + /// Example Usage: + /// const MyType& tmp = RefAnyCast<MyType>(anAny); +{ + ValueType* result = AnyCast<ValueType>(const_cast<Any*>(&operand)); + if (!result) throw BadCastException("RefAnyCast: Failed to convert between const Any types"); + return *result; +} + + +template <typename ValueType> +ValueType& RefAnyCast(Any& operand) + /// AnyCast operator used to return a reference to the internal data. + /// + /// Example Usage: + /// MyType& tmp = RefAnyCast<MyType>(anAny); +{ + ValueType* result = AnyCast<ValueType>(&operand); + if (!result) throw BadCastException("RefAnyCast: Failed to convert between Any types"); + return *result; +} + + +template <typename ValueType> +ValueType* UnsafeAnyCast(Any* operand) + /// The "unsafe" versions of AnyCast are not part of the + /// public interface and may be removed at any time. They are + /// required where we know what type is stored in the any and can't + /// use typeid() comparison, e.g., when our types may travel across + /// different shared libraries. +{ + return &static_cast<Any::Holder<ValueType>*>(operand->content())->_held; +} + + +template <typename ValueType> +const ValueType* UnsafeAnyCast(const Any* operand) + /// The "unsafe" versions of AnyCast are not part of the + /// public interface and may be removed at any time. They are + /// required where we know what type is stored in the any and can't + /// use typeid() comparison, e.g., when our types may travel across + /// different shared libraries. +{ + return AnyCast<ValueType>(const_cast<Any*>(operand)); +} + + +} // namespace Poco + + +#endif diff --git a/contrib/libs/poco/Foundation/include/Poco/ArchiveStrategy.h b/contrib/libs/poco/Foundation/include/Poco/ArchiveStrategy.h new file mode 100644 index 0000000000..e04605f38a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ArchiveStrategy.h @@ -0,0 +1,146 @@ +// +// ArchiveStrategy.h +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Definition of the ArchiveStrategy class and subclasses. +// +// Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ArchiveStrategy_INCLUDED +#define Foundation_ArchiveStrategy_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/LogFile.h" +#include "Poco/File.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/NumberFormatter.h" + + +namespace Poco { + + +class ArchiveCompressor; + + +class Foundation_API ArchiveStrategy + /// The ArchiveStrategy is used by FileChannel + /// to rename a rotated log file for archiving. + /// + /// Archived files can be automatically compressed, + /// using the gzip file format. +{ +public: + ArchiveStrategy(); + virtual ~ArchiveStrategy(); + + virtual LogFile* archive(LogFile* pFile) = 0; + /// Renames the given log file for archiving + /// and creates and returns a new log file. + /// The given LogFile object is deleted. + + void compress(bool flag = true); + /// Enables or disables compression of archived files. + +protected: + void moveFile(const std::string& oldName, const std::string& newName); + bool exists(const std::string& name); + +private: + ArchiveStrategy(const ArchiveStrategy&); + ArchiveStrategy& operator = (const ArchiveStrategy&); + + bool _compress; + ArchiveCompressor* _pCompressor; +}; + + +class Foundation_API ArchiveByNumberStrategy: public ArchiveStrategy + /// A monotonic increasing number is appended to the + /// log file name. The most recent archived file + /// always has the number zero. +{ +public: + ArchiveByNumberStrategy(); + ~ArchiveByNumberStrategy(); + LogFile* archive(LogFile* pFile); +}; + + +template <class DT> +class ArchiveByTimestampStrategy: public ArchiveStrategy + /// A timestamp (YYYYMMDDhhmmssiii) is appended to archived + /// log files. +{ +public: + ArchiveByTimestampStrategy() + { + } + + ~ArchiveByTimestampStrategy() + { + } + + LogFile* archive(LogFile* pFile) + /// Archives the file by appending the current timestamp to the + /// file name. If the new file name exists, additionally a monotonic + /// increasing number is appended to the log file name. + { + std::string path = pFile->path(); + delete pFile; + std::string archPath = path; + archPath.append("."); + DateTimeFormatter::append(archPath, DT().timestamp(), "%Y%m%d%H%M%S%i"); + + if (exists(archPath)) archiveByNumber(archPath); + else moveFile(path, archPath); + + return new LogFile(path); + } + +private: + void archiveByNumber(const std::string& basePath) + /// A monotonic increasing number is appended to the + /// log file name. The most recent archived file + /// always has the number zero. + { + int n = -1; + std::string path; + do + { + path = basePath; + path.append("."); + NumberFormatter::append(path, ++n); + } + while (exists(path)); + + while (n >= 0) + { + std::string oldPath = basePath; + if (n > 0) + { + oldPath.append("."); + NumberFormatter::append(oldPath, n - 1); + } + std::string newPath = basePath; + newPath.append("."); + NumberFormatter::append(newPath, n); + moveFile(oldPath, newPath); + --n; + } + } +}; + + +} // namespace Poco + + +#endif // Foundation_ArchiveStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Array.h b/contrib/libs/poco/Foundation/include/Poco/Array.h new file mode 100644 index 0000000000..76e5faed89 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Array.h @@ -0,0 +1,249 @@ +// +// Array.h +// +// Library: Foundation +// Package: Core +// Module: Array +// +// Definition of the Array class +// +// Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// +// ------------------------------------------------------------------------------ +// (C) Copyright Nicolai M. Josuttis 2001. +// Permission to copy, use, modify, sell and distribute this software +// is granted provided this copyright notice appears in all copies. +// This software is provided "as is" without express or implied +// warranty, and with no claim as to its suitability for any purpose. +// ------------------------------------------------------------------------------ + + +#ifndef Foundation_Array_INCLUDED +#define Foundation_Array_INCLUDED + +#include "Poco/Exception.h" +#include "Poco/Bugcheck.h" +#include <algorithm> + +namespace Poco { + +template<class T, std::size_t N> +class Array + /// STL container like C-style array replacement class. + /// + /// This implementation is based on the idea of Nicolai Josuttis. + /// His original implementation can be found at http://www.josuttis.com/cppcode/array.html . +{ + +public: + + typedef T value_type; + typedef T* iterator; + typedef const T* const_iterator; + typedef T& reference; + typedef const T& const_reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + + iterator begin() + { + return elems; + } + + const_iterator begin() const + { + return elems; + } + + iterator end() + { + return elems+N; + } + + const_iterator end() const + { + return elems+N; + } + + typedef std::reverse_iterator<iterator> reverse_iterator; + typedef std::reverse_iterator<const_iterator> const_reverse_iterator; + + reverse_iterator rbegin() + { + return reverse_iterator(end()); + } + + const_reverse_iterator rbegin() const + { + return const_reverse_iterator(end()); + } + + reverse_iterator rend() + { + return reverse_iterator(begin()); + } + + const_reverse_iterator rend() const + { + return const_reverse_iterator(begin()); + } + + reference operator[](size_type i) + /// Element access without range check. If the index is not small than the given size, the behavior is undefined. + { + poco_assert( i < N && "out of range" ); + return elems[i]; + } + + const_reference operator[](size_type i) const + /// Element access without range check. If the index is not small than the given size, the behavior is undefined. + { + poco_assert( i < N && "out of range" ); + return elems[i]; + } + + reference at(size_type i) + /// Element access with range check. Throws Poco::InvalidArgumentException if the index is over range. + { + if(i>=size()) + throw Poco::InvalidArgumentException("Array::at() range check failed: index is over range"); + return elems[i]; + } + + const_reference at(size_type i) const + /// Element access with range check. Throws Poco::InvalidArgumentException if the index is over range. + { + if(i>=size()) + throw Poco::InvalidArgumentException("Array::at() range check failed: index is over range"); + return elems[i]; + } + + reference front() + { + return elems[0]; + } + + const_reference front() const + { + return elems[0]; + } + + reference back() + { + return elems[N-1]; + } + + const_reference back() const + { + return elems[N-1]; + } + + static size_type size() + { + return N; + } + + static bool empty() + { + return false; + } + + static size_type max_size() + { + return N; + } + + enum { static_size = N }; + + void swap (Array<T,N>& y) { + std::swap_ranges(begin(),end(),y.begin()); + } + + const T* data() const + /// Direct access to data (read-only) + { + return elems; + } + + T* data() + { + return elems; + } + + T* c_array(){ + /// Use array as C array (direct read/write access to data) + return elems; + } + + template <typename Other> + Array<T,N>& operator= (const Array<Other,N>& rhs) + /// Assignment with type conversion + { + std::copy(rhs.begin(),rhs.end(), begin()); + return *this; + } + + void assign (const T& value) + /// Assign one value to all elements + { + std::fill_n(begin(),size(),value); + } + +public: + + T elems[N]; + /// Fixed-size array of elements of type T, public specifier used to make this class a aggregate. + +}; + +// comparisons +template<class T, std::size_t N> +bool operator== (const Array<T,N>& x, const Array<T,N>& y) +{ + return std::equal(x.begin(), x.end(), y.begin()); +} + +template<class T, std::size_t N> +bool operator< (const Array<T,N>& x, const Array<T,N>& y) +{ + return std::lexicographical_compare(x.begin(),x.end(),y.begin(),y.end()); +} + +template<class T, std::size_t N> +bool operator!= (const Array<T,N>& x, const Array<T,N>& y) +{ + return !(x==y); +} + +template<class T, std::size_t N> +bool operator> (const Array<T,N>& x, const Array<T,N>& y) +{ + return y<x; +} + +template<class T, std::size_t N> +bool operator<= (const Array<T,N>& x, const Array<T,N>& y) +{ + return !(y<x); +} + +template<class T, std::size_t N> +bool operator>= (const Array<T,N>& x, const Array<T,N>& y) +{ + return !(x<y); +} + +template<class T, std::size_t N> +inline void swap (Array<T,N>& x, Array<T,N>& y) + /// global swap() +{ + x.swap(y); +} + +}// namespace Poco + +#endif // Foundation_Array_INCLUDED + diff --git a/contrib/libs/poco/Foundation/include/Poco/Ascii.h b/contrib/libs/poco/Foundation/include/Poco/Ascii.h new file mode 100644 index 0000000000..5dd741df35 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Ascii.h @@ -0,0 +1,220 @@ +// +// Ascii.h +// +// Library: Foundation +// Package: Core +// Module: Ascii +// +// Definition of the Ascii class. +// +// Copyright (c) 2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Ascii_INCLUDED +#define Foundation_Ascii_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Ascii + /// This class contains enumerations and static + /// utility functions for dealing with ASCII characters + /// and their properties. + /// + /// The classification functions will also work if + /// non-ASCII character codes are passed to them, + /// but classification will only check for + /// ASCII characters. + /// + /// This allows the classification methods to be used + /// on the single bytes of a UTF-8 string, without + /// causing assertions or inconsistent results (depending + /// upon the current locale) on bytes outside the ASCII range, + /// as may be produced by Ascii::isSpace(), etc. +{ +public: + enum CharacterProperties + /// ASCII character properties. + { + ACP_CONTROL = 0x0001, + ACP_SPACE = 0x0002, + ACP_PUNCT = 0x0004, + ACP_DIGIT = 0x0008, + ACP_HEXDIGIT = 0x0010, + ACP_ALPHA = 0x0020, + ACP_LOWER = 0x0040, + ACP_UPPER = 0x0080, + ACP_GRAPH = 0x0100, + ACP_PRINT = 0x0200 + }; + + static int properties(int ch); + /// Return the ASCII character properties for the + /// character with the given ASCII value. + /// + /// If the character is outside the ASCII range + /// (0 .. 127), 0 is returned. + + static bool hasSomeProperties(int ch, int properties); + /// Returns true if the given character is + /// within the ASCII range and has at least one of + /// the given properties. + + static bool hasProperties(int ch, int properties); + /// Returns true if the given character is + /// within the ASCII range and has all of + /// the given properties. + + static bool isAscii(int ch); + /// Returns true iff the given character code is within + /// the ASCII range (0 .. 127). + + static bool isSpace(int ch); + /// Returns true iff the given character is a whitespace. + + static bool isDigit(int ch); + /// Returns true iff the given character is a digit. + + static bool isHexDigit(int ch); + /// Returns true iff the given character is a hexadecimal digit. + + static bool isPunct(int ch); + /// Returns true iff the given character is a punctuation character. + + static bool isAlpha(int ch); + /// Returns true iff the given character is an alphabetic character. + + static bool isAlphaNumeric(int ch); + /// Returns true iff the given character is an alphabetic character. + + static bool isLower(int ch); + /// Returns true iff the given character is a lowercase alphabetic + /// character. + + static bool isUpper(int ch); + /// Returns true iff the given character is an uppercase alphabetic + /// character. + + static int toLower(int ch); + /// If the given character is an uppercase character, + /// return its lowercase counterpart, otherwise return + /// the character. + + static int toUpper(int ch); + /// If the given character is a lowercase character, + /// return its uppercase counterpart, otherwise return + /// the character. + +private: + static const int CHARACTER_PROPERTIES[128]; +}; + + +// +// inlines +// +inline int Ascii::properties(int ch) +{ + if (isAscii(ch)) + return CHARACTER_PROPERTIES[ch]; + else + return 0; +} + + +inline bool Ascii::isAscii(int ch) +{ + return (static_cast<UInt32>(ch) & 0xFFFFFF80) == 0; +} + + +inline bool Ascii::hasProperties(int ch, int props) +{ + return (properties(ch) & props) == props; +} + + +inline bool Ascii::hasSomeProperties(int ch, int props) +{ + return (properties(ch) & props) != 0; +} + + +inline bool Ascii::isSpace(int ch) +{ + return hasProperties(ch, ACP_SPACE); +} + + +inline bool Ascii::isDigit(int ch) +{ + return hasProperties(ch, ACP_DIGIT); +} + + +inline bool Ascii::isHexDigit(int ch) +{ + return hasProperties(ch, ACP_HEXDIGIT); +} + + +inline bool Ascii::isPunct(int ch) +{ + return hasProperties(ch, ACP_PUNCT); +} + + +inline bool Ascii::isAlpha(int ch) +{ + return hasProperties(ch, ACP_ALPHA); +} + + +inline bool Ascii::isAlphaNumeric(int ch) +{ + return hasSomeProperties(ch, ACP_ALPHA | ACP_DIGIT); +} + + +inline bool Ascii::isLower(int ch) +{ + return hasProperties(ch, ACP_LOWER); +} + + +inline bool Ascii::isUpper(int ch) +{ + return hasProperties(ch, ACP_UPPER); +} + + +inline int Ascii::toLower(int ch) +{ + if (isUpper(ch)) + return ch + 32; + else + return ch; +} + + +inline int Ascii::toUpper(int ch) +{ + if (isLower(ch)) + return ch - 32; + else + return ch; +} + + +} // namespace Poco + + +#endif // Foundation_Ascii_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AsyncChannel.h b/contrib/libs/poco/Foundation/include/Poco/AsyncChannel.h new file mode 100644 index 0000000000..9756edc3eb --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AsyncChannel.h @@ -0,0 +1,100 @@ +// +// AsyncChannel.h +// +// Library: Foundation +// Package: Logging +// Module: AsyncChannel +// +// Definition of the AsyncChannel class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AsyncChannel_INCLUDED +#define Foundation_AsyncChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Thread.h" +#include "Poco/Mutex.h" +#include "Poco/Runnable.h" +#include "Poco/NotificationQueue.h" + + +namespace Poco { + + +class Foundation_API AsyncChannel: public Channel, public Runnable + /// A channel uses a separate thread for logging. + /// + /// Using this channel can help to improve the performance of + /// applications that produce huge amounts of log messages or + /// that write log messages to multiple channels simultaneously. + /// + /// All log messages are put into a queue and this queue is + /// then processed by a separate thread. +{ +public: + AsyncChannel(Channel* pChannel = 0, Thread::Priority prio = Thread::PRIO_NORMAL); + /// Creates the AsyncChannel and connects it to + /// the given channel. + + void setChannel(Channel* pChannel); + /// Connects the AsyncChannel to the given target channel. + /// All messages will be forwarded to this channel. + + Channel* getChannel() const; + /// Returns the target channel. + + void open(); + /// Opens the channel and creates the + /// background logging thread. + + void close(); + /// Closes the channel and stops the background + /// logging thread. + + void log(const Message& msg); + /// Queues the message for processing by the + /// background thread. + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// The "channel" property allows setting the target + /// channel via the LoggingRegistry. + /// The "channel" property is set-only. + /// + /// The "priority" property allows setting the thread + /// priority. The following values are supported: + /// * lowest + /// * low + /// * normal (default) + /// * high + /// * highest + /// + /// The "priority" property is set-only. + +protected: + ~AsyncChannel(); + void run(); + void setPriority(const std::string& value); + +private: + Channel* _pChannel; + Thread _thread; + FastMutex _threadMutex; + FastMutex _channelMutex; + NotificationQueue _queue; +}; + + +} // namespace Poco + + +#endif // Foundation_AsyncChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AtomicCounter.h b/contrib/libs/poco/Foundation/include/Poco/AtomicCounter.h new file mode 100644 index 0000000000..4c7c7884f0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AtomicCounter.h @@ -0,0 +1,417 @@ +// +// AtomicCounter.h +// +// Library: Foundation +// Package: Core +// Module: AtomicCounter +// +// Definition of the AtomicCounter class. +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AtomicCounter_INCLUDED +#define Foundation_AtomicCounter_INCLUDED + + +#include "Poco/Foundation.h" +#if POCO_OS == POCO_OS_WINDOWS_NT + #include "Poco/UnWindows.h" +#elif POCO_OS == POCO_OS_MAC_OS_X + #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000 || __TV_OS_VERSION_MAX_ALLOWED >= 100000 || __WATCH_OS_VERSION_MAX_ALLOWED >= 30000 + #if __cplusplus >= 201103L + #ifndef POCO_HAVE_STD_ATOMICS + #define POCO_HAVE_STD_ATOMICS + #endif + #else + #include <libkern/OSAtomic.h> + #endif + #else + #include <libkern/OSAtomic.h> + #endif +#elif ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2) || __GNUC__ > 4) && (defined(__x86_64__) || defined(__i386__)) + #if !defined(POCO_HAVE_GCC_ATOMICS) && !defined(POCO_NO_GCC_ATOMICS) + #define POCO_HAVE_GCC_ATOMICS + #endif +#elif ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3) || __GNUC__ > 4) + #if !defined(POCO_HAVE_GCC_ATOMICS) && !defined(POCO_NO_GCC_ATOMICS) + #define POCO_HAVE_GCC_ATOMICS + #endif +#endif // POCO_OS +#include "Poco/Mutex.h" +#ifdef POCO_HAVE_STD_ATOMICS +#include <atomic> +#endif + + +namespace Poco { + + +class Foundation_API AtomicCounter + /// This class implements a simple counter, which + /// provides atomic operations that are safe to + /// use in a multithreaded environment. + /// + /// Typical usage of AtomicCounter is for implementing + /// reference counting and similar things. + /// + /// On some platforms, the implementation of AtomicCounter + /// is based on atomic primitives specific to the platform + /// (such as InterlockedIncrement, etc. on Windows), and + /// thus very efficient. On platforms that do not support + /// atomic primitives, operations are guarded by a FastMutex. + /// + /// The following platforms currently have atomic + /// primitives: + /// - Windows + /// - Mac OS X + /// - GCC 4.1+ (Intel platforms only) +{ +public: + typedef int ValueType; /// The underlying integer type. + + AtomicCounter(); + /// Creates a new AtomicCounter and initializes it to zero. + + explicit AtomicCounter(ValueType initialValue); + /// Creates a new AtomicCounter and initializes it with + /// the given value. + + AtomicCounter(const AtomicCounter& counter); + /// Creates the counter by copying another one. + + ~AtomicCounter(); + /// Destroys the AtomicCounter. + + AtomicCounter& operator = (const AtomicCounter& counter); + /// Assigns the value of another AtomicCounter. + + AtomicCounter& operator = (ValueType value); + /// Assigns a value to the counter. + + operator ValueType () const; + /// Returns the value of the counter. + + ValueType value() const; + /// Returns the value of the counter. + + ValueType operator ++ (); // prefix + /// Increments the counter and returns the result. + + ValueType operator ++ (int); // postfix + /// Increments the counter and returns the previous value. + + ValueType operator -- (); // prefix + /// Decrements the counter and returns the result. + + ValueType operator -- (int); // postfix + /// Decrements the counter and returns the previous value. + + bool operator ! () const; + /// Returns true if the counter is zero, false otherwise. + +private: +#if defined(POCO_HAVE_STD_ATOMICS) + typedef std::atomic<int> ImplType; +#elif POCO_OS == POCO_OS_WINDOWS_NT + typedef volatile LONG ImplType; +#elif POCO_OS == POCO_OS_MAC_OS_X + typedef int32_t ImplType; +#elif defined(POCO_HAVE_GCC_ATOMICS) + typedef int ImplType; +#else // generic implementation based on FastMutex + struct ImplType + { + mutable FastMutex mutex; + volatile int value; + }; +#endif // POCO_OS + + ImplType _counter; +}; + + +// +// inlines +// + + +#if defined(POCO_HAVE_STD_ATOMICS) +// +// C++11 atomics +// +inline AtomicCounter::operator AtomicCounter::ValueType () const +{ + return _counter.load(); +} + + +inline AtomicCounter::ValueType AtomicCounter::value() const +{ + return _counter.load(); +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ () // prefix +{ + return ++_counter; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ (int) // postfix +{ + return _counter++; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- () // prefix +{ + return --_counter; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- (int) // postfix +{ + return _counter--; +} + + +inline bool AtomicCounter::operator ! () const +{ + return _counter.load() == 0; +} + + +#elif POCO_OS == POCO_OS_WINDOWS_NT +// +// Windows +// +inline AtomicCounter::operator AtomicCounter::ValueType () const +{ + return _counter; +} + + +inline AtomicCounter::ValueType AtomicCounter::value() const +{ + return _counter; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ () // prefix +{ + return InterlockedIncrement(&_counter); +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ (int) // postfix +{ + ValueType result = InterlockedIncrement(&_counter); + return --result; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- () // prefix +{ + return InterlockedDecrement(&_counter); +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- (int) // postfix +{ + ValueType result = InterlockedDecrement(&_counter); + return ++result; +} + + +inline bool AtomicCounter::operator ! () const +{ + return _counter == 0; +} + + +#elif POCO_OS == POCO_OS_MAC_OS_X +// +// Mac OS X +// +inline AtomicCounter::operator AtomicCounter::ValueType () const +{ + return _counter; +} + + +inline AtomicCounter::ValueType AtomicCounter::value() const +{ + return _counter; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ () // prefix +{ + return OSAtomicIncrement32(&_counter); +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ (int) // postfix +{ + ValueType result = OSAtomicIncrement32(&_counter); + return --result; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- () // prefix +{ + return OSAtomicDecrement32(&_counter); +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- (int) // postfix +{ + ValueType result = OSAtomicDecrement32(&_counter); + return ++result; +} + + +inline bool AtomicCounter::operator ! () const +{ + return _counter == 0; +} + +#elif defined(POCO_HAVE_GCC_ATOMICS) +// +// GCC 4.1+ atomic builtins. +// +inline AtomicCounter::operator AtomicCounter::ValueType () const +{ + return _counter; +} + + +inline AtomicCounter::ValueType AtomicCounter::value() const +{ + return _counter; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ () // prefix +{ + return __sync_add_and_fetch(&_counter, 1); +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ (int) // postfix +{ + return __sync_fetch_and_add(&_counter, 1); +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- () // prefix +{ + return __sync_sub_and_fetch(&_counter, 1); +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- (int) // postfix +{ + return __sync_fetch_and_sub(&_counter, 1); +} + + +inline bool AtomicCounter::operator ! () const +{ + return _counter == 0; +} + + +#else +// +// Generic implementation based on FastMutex +// +inline AtomicCounter::operator AtomicCounter::ValueType () const +{ + ValueType result; + { + FastMutex::ScopedLock lock(_counter.mutex); + result = _counter.value; + } + return result; +} + + +inline AtomicCounter::ValueType AtomicCounter::value() const +{ + ValueType result; + { + FastMutex::ScopedLock lock(_counter.mutex); + result = _counter.value; + } + return result; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ () // prefix +{ + ValueType result; + { + FastMutex::ScopedLock lock(_counter.mutex); + result = ++_counter.value; + } + return result; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator ++ (int) // postfix +{ + ValueType result; + { + FastMutex::ScopedLock lock(_counter.mutex); + result = _counter.value++; + } + return result; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- () // prefix +{ + ValueType result; + { + FastMutex::ScopedLock lock(_counter.mutex); + result = --_counter.value; + } + return result; +} + + +inline AtomicCounter::ValueType AtomicCounter::operator -- (int) // postfix +{ + ValueType result; + { + FastMutex::ScopedLock lock(_counter.mutex); + result = _counter.value--; + } + return result; +} + + +inline bool AtomicCounter::operator ! () const +{ + bool result; + { + FastMutex::ScopedLock lock(_counter.mutex); + result = _counter.value == 0; + } + return result; +} + + +#endif // POCO_OS + + +} // namespace Poco + + +#endif // Foundation_AtomicCounter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AutoPtr.h b/contrib/libs/poco/Foundation/include/Poco/AutoPtr.h new file mode 100644 index 0000000000..c3235715ab --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AutoPtr.h @@ -0,0 +1,386 @@ +// +// AutoPtr.h +// +// Library: Foundation +// Package: Core +// Module: AutoPtr +// +// Definition of the AutoPtr template class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AutoPtr_INCLUDED +#define Foundation_AutoPtr_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <algorithm> + + +namespace Poco { + + +template <class C> +class AutoPtr + /// AutoPtr is a "smart" pointer for classes implementing + /// reference counting based garbage collection. + /// To be usable with the AutoPtr template, a class must + /// implement the following behaviour: + /// A class must maintain a reference count. + /// The constructors of the object initialize the reference + /// count to one. + /// The class must implement a public duplicate() method: + /// void duplicate(); + /// that increments the reference count by one. + /// The class must implement a public release() method: + /// void release() + /// that decrements the reference count by one, and, + /// if the reference count reaches zero, deletes the + /// object. + /// + /// AutoPtr works in the following way: + /// If an AutoPtr is assigned an ordinary pointer to + /// an object (via the constructor or the assignment operator), + /// it takes ownership of the object and the object's reference + /// count remains unchanged. + /// If the AutoPtr is assigned another AutoPtr, the + /// object's reference count is incremented by one by + /// calling duplicate() on its object. + /// The destructor of AutoPtr calls release() on its + /// object. + /// AutoPtr supports dereferencing with both the -> + /// and the * operator. An attempt to dereference a null + /// AutoPtr results in a NullPointerException being thrown. + /// AutoPtr also implements all relational operators. + /// Note that AutoPtr allows casting of its encapsulated data types. +{ +public: + AutoPtr(): _ptr(0) + { + } + + AutoPtr(C* ptr): _ptr(ptr) + { + } + + AutoPtr(C* ptr, bool shared): _ptr(ptr) + { + if (shared && _ptr) _ptr->duplicate(); + } + + AutoPtr(const AutoPtr& ptr): _ptr(ptr._ptr) + { + if (_ptr) _ptr->duplicate(); + } + + template <class Other> + AutoPtr(const AutoPtr<Other>& ptr): _ptr(const_cast<Other*>(ptr.get())) + { + if (_ptr) _ptr->duplicate(); + } + + ~AutoPtr() + { + if (_ptr) _ptr->release(); + } + + AutoPtr& assign(C* ptr) + { + if (_ptr != ptr) + { + if (_ptr) _ptr->release(); + _ptr = ptr; + } + return *this; + } + + AutoPtr& assign(C* ptr, bool shared) + { + if (_ptr != ptr) + { + if (_ptr) _ptr->release(); + _ptr = ptr; + if (shared && _ptr) _ptr->duplicate(); + } + return *this; + } + + AutoPtr& assign(const AutoPtr& ptr) + { + if (&ptr != this) + { + if (_ptr) _ptr->release(); + _ptr = ptr._ptr; + if (_ptr) _ptr->duplicate(); + } + return *this; + } + + template <class Other> + AutoPtr& assign(const AutoPtr<Other>& ptr) + { + if (ptr.get() != _ptr) + { + if (_ptr) _ptr->release(); + _ptr = const_cast<Other*>(ptr.get()); + if (_ptr) _ptr->duplicate(); + } + return *this; + } + + void reset() + { + if (_ptr) + { + _ptr->release(); + _ptr = 0; + } + } + + void reset(C* ptr) + { + assign(ptr); + } + + void reset(C* ptr, bool shared) + { + assign(ptr, shared); + } + + void reset(const AutoPtr& ptr) + { + assign(ptr); + } + + template <class Other> + void reset(const AutoPtr<Other>& ptr) + { + assign<Other>(ptr); + } + + AutoPtr& operator = (C* ptr) + { + return assign(ptr); + } + + AutoPtr& operator = (const AutoPtr& ptr) + { + return assign(ptr); + } + + template <class Other> + AutoPtr& operator = (const AutoPtr<Other>& ptr) + { + return assign<Other>(ptr); + } + + void swap(AutoPtr& ptr) + { + std::swap(_ptr, ptr._ptr); + } + + template <class Other> + AutoPtr<Other> cast() const + /// Casts the AutoPtr via a dynamic cast to the given type. + /// Returns an AutoPtr containing NULL if the cast fails. + /// Example: (assume class Sub: public Super) + /// AutoPtr<Super> super(new Sub()); + /// AutoPtr<Sub> sub = super.cast<Sub>(); + /// poco_assert (sub.get()); + { + Other* pOther = dynamic_cast<Other*>(_ptr); + return AutoPtr<Other>(pOther, true); + } + + template <class Other> + AutoPtr<Other> unsafeCast() const + /// Casts the AutoPtr via a static cast to the given type. + /// Example: (assume class Sub: public Super) + /// AutoPtr<Super> super(new Sub()); + /// AutoPtr<Sub> sub = super.unsafeCast<Sub>(); + /// poco_assert (sub.get()); + { + Other* pOther = static_cast<Other*>(_ptr); + return AutoPtr<Other>(pOther, true); + } + + C* operator -> () + { + if (_ptr) + return _ptr; + else + throw NullPointerException(); + } + + const C* operator -> () const + { + if (_ptr) + return _ptr; + else + throw NullPointerException(); + } + + C& operator * () + { + if (_ptr) + return *_ptr; + else + throw NullPointerException(); + } + + const C& operator * () const + { + if (_ptr) + return *_ptr; + else + throw NullPointerException(); + } + + C* get() + { + return _ptr; + } + + const C* get() const + { + return _ptr; + } + + operator C* () + { + return _ptr; + } + + operator const C* () const + { + return _ptr; + } + + bool operator ! () const + { + return _ptr == 0; + } + + bool isNull() const + { + return _ptr == 0; + } + + C* duplicate() + { + if (_ptr) _ptr->duplicate(); + return _ptr; + } + + bool operator == (const AutoPtr& ptr) const + { + return _ptr == ptr._ptr; + } + + bool operator == (const C* ptr) const + { + return _ptr == ptr; + } + + bool operator == (C* ptr) const + { + return _ptr == ptr; + } + + bool operator != (const AutoPtr& ptr) const + { + return _ptr != ptr._ptr; + } + + bool operator != (const C* ptr) const + { + return _ptr != ptr; + } + + bool operator != (C* ptr) const + { + return _ptr != ptr; + } + + bool operator < (const AutoPtr& ptr) const + { + return _ptr < ptr._ptr; + } + + bool operator < (const C* ptr) const + { + return _ptr < ptr; + } + + bool operator < (C* ptr) const + { + return _ptr < ptr; + } + + bool operator <= (const AutoPtr& ptr) const + { + return _ptr <= ptr._ptr; + } + + bool operator <= (const C* ptr) const + { + return _ptr <= ptr; + } + + bool operator <= (C* ptr) const + { + return _ptr <= ptr; + } + + bool operator > (const AutoPtr& ptr) const + { + return _ptr > ptr._ptr; + } + + bool operator > (const C* ptr) const + { + return _ptr > ptr; + } + + bool operator > (C* ptr) const + { + return _ptr > ptr; + } + + bool operator >= (const AutoPtr& ptr) const + { + return _ptr >= ptr._ptr; + } + + bool operator >= (const C* ptr) const + { + return _ptr >= ptr; + } + + bool operator >= (C* ptr) const + { + return _ptr >= ptr; + } + +private: + C* _ptr; +}; + + +template <class C> +inline void swap(AutoPtr<C>& p1, AutoPtr<C>& p2) +{ + p1.swap(p2); +} + + +} // namespace Poco + + +#endif // Foundation_AutoPtr_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/AutoReleasePool.h b/contrib/libs/poco/Foundation/include/Poco/AutoReleasePool.h new file mode 100644 index 0000000000..0b13956e8e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/AutoReleasePool.h @@ -0,0 +1,86 @@ +// +// AutoReleasePool.h +// +// Library: Foundation +// Package: Core +// Module: AutoReleasePool +// +// Definition of the AutoReleasePool class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_AutoReleasePool_INCLUDED +#define Foundation_AutoReleasePool_INCLUDED + + +#include "Poco/Foundation.h" +#include <list> + + +namespace Poco { + + +template <class C> +class AutoReleasePool + /// An AutoReleasePool implements simple garbage collection for + /// reference-counted objects. + /// It temporarily takes ownwership of reference-counted objects that + /// nobody else wants to take ownership of and releases them + /// at a later, appropriate point in time. + /// + /// Note: The correct way to add an object hold by an AutoPtr<> to + /// an AutoReleasePool is by invoking the AutoPtr's duplicate() + /// method. Example: + /// AutoReleasePool<C> arp; + /// AutoPtr<C> ptr = new C; + /// ... + /// arp.add(ptr.duplicate()); +{ +public: + AutoReleasePool() + /// Creates the AutoReleasePool. + { + } + + ~AutoReleasePool() + /// Destroys the AutoReleasePool and releases + /// all objects it currently holds. + { + release(); + } + + void add(C* pObject) + /// Adds the given object to the AutoReleasePool. + /// The object's reference count is not modified + { + if (pObject) + _list.push_back(pObject); + } + + void release() + /// Releases all objects the AutoReleasePool currently holds + /// by calling each object's release() method. + { + while (!_list.empty()) + { + _list.front()->release(); + _list.pop_front(); + } + } + +private: + typedef std::list<C*> ObjectList; + + ObjectList _list; +}; + + +} // namespace Poco + + +#endif // Foundation_AutoReleasePool_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Base32Decoder.h b/contrib/libs/poco/Foundation/include/Poco/Base32Decoder.h new file mode 100644 index 0000000000..54367c5886 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Base32Decoder.h @@ -0,0 +1,104 @@ +// +// Base32Decoder.h +// +// Library: Foundation +// Package: Streams +// Module: Base32 +// +// Definition of class Base32Decoder. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Base32Decoder_INCLUDED +#define Foundation_Base32Decoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <istream> + + +namespace Poco { + + +class Foundation_API Base32DecoderBuf: public UnbufferedStreamBuf + /// This streambuf base32-decodes all data read + /// from the istream connected to it. + /// + /// Note: For performance reasons, the characters + /// are read directly from the given istream's + /// underlying streambuf, so the state + /// of the istream will not reflect that of + /// its streambuf. +{ +public: + Base32DecoderBuf(std::istream& istr); + ~Base32DecoderBuf(); + +private: + int readFromDevice(); + int readOne(); + + unsigned char _group[8]; + int _groupLength; + int _groupIndex; + std::streambuf& _buf; + + static unsigned char IN_ENCODING[256]; + static bool IN_ENCODING_INIT; + +private: + Base32DecoderBuf(const Base32DecoderBuf&); + Base32DecoderBuf& operator = (const Base32DecoderBuf&); +}; + + +class Foundation_API Base32DecoderIOS: public virtual std::ios + /// The base class for Base32Decoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + Base32DecoderIOS(std::istream& istr); + ~Base32DecoderIOS(); + Base32DecoderBuf* rdbuf(); + +protected: + Base32DecoderBuf _buf; + +private: + Base32DecoderIOS(const Base32DecoderIOS&); + Base32DecoderIOS& operator = (const Base32DecoderIOS&); +}; + + +class Foundation_API Base32Decoder: public Base32DecoderIOS, public std::istream + /// This istream base32-decodes all data + /// read from the istream connected to it. + /// + /// Note: For performance reasons, the characters + /// are read directly from the given istream's + /// underlying streambuf, so the state + /// of the istream will not reflect that of + /// its streambuf. +{ +public: + Base32Decoder(std::istream& istr); + ~Base32Decoder(); + +private: + Base32Decoder(const Base32Decoder&); + Base32Decoder& operator = (const Base32Decoder&); +}; + + +} // namespace Poco + + +#endif // Foundation_Base32Decoder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Base32Encoder.h b/contrib/libs/poco/Foundation/include/Poco/Base32Encoder.h new file mode 100644 index 0000000000..246f8483b0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Base32Encoder.h @@ -0,0 +1,110 @@ +// +// Base32Encoder.h +// +// Library: Foundation +// Package: Streams +// Module: Base32 +// +// Definition of class Base32Encoder. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Base32Encoder_INCLUDED +#define Foundation_Base32Encoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <ostream> + + +namespace Poco { + + +class Foundation_API Base32EncoderBuf: public UnbufferedStreamBuf + /// This streambuf base32-encodes all data written + /// to it and forwards it to a connected + /// ostream. + /// + /// Note: The characters are directly written + /// to the ostream's streambuf, thus bypassing + /// the ostream. The ostream's state is therefore + /// not updated to match the buffer's state. +{ +public: + Base32EncoderBuf(std::ostream& ostr, bool padding = true); + ~Base32EncoderBuf(); + + int close(); + /// Closes the stream buffer. + +private: + int writeToDevice(char c); + + unsigned char _group[5]; + int _groupLength; + std::streambuf& _buf; + bool _doPadding; + + static const unsigned char OUT_ENCODING[32]; + + friend class Base32DecoderBuf; + + Base32EncoderBuf(const Base32EncoderBuf&); + Base32EncoderBuf& operator = (const Base32EncoderBuf&); +}; + + +class Foundation_API Base32EncoderIOS: public virtual std::ios + /// The base class for Base32Encoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + Base32EncoderIOS(std::ostream& ostr, bool padding = true); + ~Base32EncoderIOS(); + int close(); + Base32EncoderBuf* rdbuf(); + +protected: + Base32EncoderBuf _buf; + +private: + Base32EncoderIOS(const Base32EncoderIOS&); + Base32EncoderIOS& operator = (const Base32EncoderIOS&); +}; + + +class Foundation_API Base32Encoder: public Base32EncoderIOS, public std::ostream + /// This ostream base32-encodes all data + /// written to it and forwards it to + /// a connected ostream. + /// Always call close() when done + /// writing data, to ensure proper + /// completion of the encoding operation. + /// + /// Note: The characters are directly written + /// to the ostream's streambuf, thus bypassing + /// the ostream. The ostream's state is therefore + /// not updated to match the buffer's state. +{ +public: + Base32Encoder(std::ostream& ostr, bool padding = true); + ~Base32Encoder(); + +private: + Base32Encoder(const Base32Encoder&); + Base32Encoder& operator = (const Base32Encoder&); +}; + + +} // namespace Poco + + +#endif // Foundation_Base32Encoder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Base64Decoder.h b/contrib/libs/poco/Foundation/include/Poco/Base64Decoder.h new file mode 100644 index 0000000000..51958231e0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Base64Decoder.h @@ -0,0 +1,108 @@ +// +// Base64Decoder.h +// +// Library: Foundation +// Package: Streams +// Module: Base64 +// +// Definition of class Base64Decoder. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Base64Decoder_INCLUDED +#define Foundation_Base64Decoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <istream> + + +namespace Poco { + + +class Foundation_API Base64DecoderBuf: public UnbufferedStreamBuf + /// This streambuf base64-decodes all data read + /// from the istream connected to it. + /// + /// Note: For performance reasons, the characters + /// are read directly from the given istream's + /// underlying streambuf, so the state + /// of the istream will not reflect that of + /// its streambuf. +{ +public: + Base64DecoderBuf(std::istream& istr, int options = 0); + ~Base64DecoderBuf(); + +private: + int readFromDevice(); + int readOne(); + + int _options; + unsigned char _group[3]; + int _groupLength; + int _groupIndex; + std::streambuf& _buf; + const unsigned char* _pInEncoding; + + static unsigned char IN_ENCODING[256]; + static bool IN_ENCODING_INIT; + static unsigned char IN_ENCODING_URL[256]; + static bool IN_ENCODING_URL_INIT; + +private: + Base64DecoderBuf(const Base64DecoderBuf&); + Base64DecoderBuf& operator = (const Base64DecoderBuf&); +}; + + +class Foundation_API Base64DecoderIOS: public virtual std::ios + /// The base class for Base64Decoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + Base64DecoderIOS(std::istream& istr, int options = 0); + ~Base64DecoderIOS(); + Base64DecoderBuf* rdbuf(); + +protected: + Base64DecoderBuf _buf; + +private: + Base64DecoderIOS(const Base64DecoderIOS&); + Base64DecoderIOS& operator = (const Base64DecoderIOS&); +}; + + +class Foundation_API Base64Decoder: public Base64DecoderIOS, public std::istream + /// This istream base64-decodes all data + /// read from the istream connected to it. + /// + /// Note: For performance reasons, the characters + /// are read directly from the given istream's + /// underlying streambuf, so the state + /// of the istream will not reflect that of + /// its streambuf. +{ +public: + Base64Decoder(std::istream& istr, int options = 0); + ~Base64Decoder(); + +private: + Base64Decoder(const Base64Decoder&); + Base64Decoder& operator = (const Base64Decoder&); +}; + + +} // namespace Poco + + +#endif // Foundation_Base64Decoder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Base64Encoder.h b/contrib/libs/poco/Foundation/include/Poco/Base64Encoder.h new file mode 100644 index 0000000000..4371803a59 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Base64Encoder.h @@ -0,0 +1,138 @@ +// +// Base64Encoder.h +// +// Library: Foundation +// Package: Streams +// Module: Base64 +// +// Definition of class Base64Encoder. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Base64Encoder_INCLUDED +#define Foundation_Base64Encoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <ostream> + + +namespace Poco { + + +enum Base64EncodingOptions +{ + BASE64_URL_ENCODING = 0x01, + /// Use the URL and filename-safe alphabet, + /// replacing '+' with '-' and '/' with '_'. + /// + /// Will also set line length to unlimited. + + BASE64_NO_PADDING = 0x02 + /// Do not append padding characters ('=') at end. +}; + + +class Foundation_API Base64EncoderBuf: public UnbufferedStreamBuf + /// This streambuf base64-encodes all data written + /// to it and forwards it to a connected + /// ostream. + /// + /// Note: The characters are directly written + /// to the ostream's streambuf, thus bypassing + /// the ostream. The ostream's state is therefore + /// not updated to match the buffer's state. +{ +public: + Base64EncoderBuf(std::ostream& ostr, int options = 0); + ~Base64EncoderBuf(); + + int close(); + /// Closes the stream buffer. + + void setLineLength(int lineLength); + /// Specify the line length. + /// + /// After the given number of characters have been written, + /// a newline character will be written. + /// + /// Specify 0 for an unlimited line length. + + int getLineLength() const; + /// Returns the currently set line length. + +private: + int writeToDevice(char c); + + int _options; + unsigned char _group[3]; + int _groupLength; + int _pos; + int _lineLength; + std::streambuf& _buf; + const unsigned char* _pOutEncoding; + + static const unsigned char OUT_ENCODING[64]; + static const unsigned char OUT_ENCODING_URL[64]; + + friend class Base64DecoderBuf; + + Base64EncoderBuf(const Base64EncoderBuf&); + Base64EncoderBuf& operator = (const Base64EncoderBuf&); +}; + + +class Foundation_API Base64EncoderIOS: public virtual std::ios + /// The base class for Base64Encoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + Base64EncoderIOS(std::ostream& ostr, int options = 0); + ~Base64EncoderIOS(); + int close(); + Base64EncoderBuf* rdbuf(); + +protected: + Base64EncoderBuf _buf; + +private: + Base64EncoderIOS(const Base64EncoderIOS&); + Base64EncoderIOS& operator = (const Base64EncoderIOS&); +}; + + +class Foundation_API Base64Encoder: public Base64EncoderIOS, public std::ostream + /// This ostream base64-encodes all data + /// written to it and forwards it to + /// a connected ostream. + /// Always call close() when done + /// writing data, to ensure proper + /// completion of the encoding operation. + /// + /// Note: The characters are directly written + /// to the ostream's streambuf, thus bypassing + /// the ostream. The ostream's state is therefore + /// not updated to match the buffer's state. +{ +public: + Base64Encoder(std::ostream& ostr, int options = 0); + ~Base64Encoder(); + +private: + Base64Encoder(const Base64Encoder&); + Base64Encoder& operator = (const Base64Encoder&); +}; + + +} // namespace Poco + + +#endif // Foundation_Base64Encoder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/BasicEvent.h b/contrib/libs/poco/Foundation/include/Poco/BasicEvent.h new file mode 100644 index 0000000000..bc2dd516c3 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/BasicEvent.h @@ -0,0 +1,60 @@ +// +// BasicEvent.h +// +// Library: Foundation +// Package: Events +// Module: BasicEvent +// +// Implementation of the BasicEvent template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_BasicEvent_INCLUDED +#define Foundation_BasicEvent_INCLUDED + + +#include "Poco/AbstractEvent.h" +#include "Poco/DefaultStrategy.h" +#include "Poco/AbstractDelegate.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class TArgs, class TMutex = FastMutex> +class BasicEvent: public AbstractEvent < + TArgs, DefaultStrategy<TArgs, AbstractDelegate<TArgs> >, + AbstractDelegate<TArgs>, + TMutex +> + /// A BasicEvent uses the DefaultStrategy which + /// invokes delegates in the order they have been registered. + /// + /// Please see the AbstractEvent class template documentation + /// for more information. +{ +public: + BasicEvent() + { + } + + ~BasicEvent() + { + } + +private: + BasicEvent(const BasicEvent& e); + BasicEvent& operator = (const BasicEvent& e); +}; + + +} // namespace Poco + + +#endif // Foundation_BasicEvent_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/BinaryReader.h b/contrib/libs/poco/Foundation/include/Poco/BinaryReader.h new file mode 100644 index 0000000000..b4d0fb1d82 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/BinaryReader.h @@ -0,0 +1,265 @@ +// +// BinaryReader.h +// +// Library: Foundation +// Package: Streams +// Module: BinaryReaderWriter +// +// Definition of the BinaryReader class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_BinaryReader_INCLUDED +#define Foundation_BinaryReader_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Buffer.h" +#include "Poco/MemoryStream.h" +#include <vector> +#include <istream> + + +namespace Poco { + + +class TextEncoding; +class TextConverter; + + +class Foundation_API BinaryReader + /// This class reads basic types (and std::vectors thereof) + /// in binary form into an input stream. + /// It provides an extractor-based interface similar to istream. + /// The reader also supports automatic conversion from big-endian + /// (network byte order) to little-endian and vice-versa. + /// Use a BinaryWriter to create a stream suitable for a BinaryReader. +{ +public: + enum StreamByteOrder + { + NATIVE_BYTE_ORDER = 1, /// the host's native byte-order + BIG_ENDIAN_BYTE_ORDER = 2, /// big-endian (network) byte-order + NETWORK_BYTE_ORDER = 2, /// big-endian (network) byte-order + LITTLE_ENDIAN_BYTE_ORDER = 3, /// little-endian byte-order + UNSPECIFIED_BYTE_ORDER = 4 /// unknown, byte-order will be determined by reading the byte-order mark + }; + + BinaryReader(std::istream& istr, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER); + /// Creates the BinaryReader. + + BinaryReader(std::istream& istr, TextEncoding& encoding, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER); + /// Creates the BinaryReader using the given TextEncoding. + /// + /// Strings will be converted from the specified encoding + /// to the currently set global encoding (see Poco::TextEncoding::global()). + + ~BinaryReader(); + /// Destroys the BinaryReader. + + BinaryReader& operator >> (bool& value); + BinaryReader& operator >> (char& value); + BinaryReader& operator >> (unsigned char& value); + BinaryReader& operator >> (signed char& value); + BinaryReader& operator >> (short& value); + BinaryReader& operator >> (unsigned short& value); + BinaryReader& operator >> (int& value); + BinaryReader& operator >> (unsigned int& value); + BinaryReader& operator >> (long& value); + BinaryReader& operator >> (unsigned long& value); + BinaryReader& operator >> (float& value); + BinaryReader& operator >> (double& value); + +#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + BinaryReader& operator >> (Int64& value); + BinaryReader& operator >> (UInt64& value); +#endif + + BinaryReader& operator >> (std::string& value); + + template <typename T> + BinaryReader& operator >> (std::vector<T>& value) + { + Poco::UInt32 size(0); + T elem; + + *this >> size; + if (!good()) return *this; + value.reserve(size); + while (this->good() && size-- > 0) + { + *this >> elem; + value.push_back(elem); + } + return *this; + } + + void read7BitEncoded(UInt32& value); + /// Reads a 32-bit unsigned integer in compressed format. + /// See BinaryWriter::write7BitEncoded() for a description + /// of the compression algorithm. + +#if defined(POCO_HAVE_INT64) + void read7BitEncoded(UInt64& value); + /// Reads a 64-bit unsigned integer in compressed format. + /// See BinaryWriter::write7BitEncoded() for a description + /// of the compression algorithm. +#endif + + void readRaw(std::streamsize length, std::string& value); + /// Reads length bytes of raw data into value. + + void readRaw(char* buffer, std::streamsize length); + /// Reads length bytes of raw data into buffer. + + void readBOM(); + /// Reads a byte-order mark from the stream and configures + /// the reader for the encountered byte order. + /// A byte-order mark is a 16-bit integer with a value of 0xFEFF, + /// written in host byte order. + + bool good(); + /// Returns _istr.good(); + + bool fail(); + /// Returns _istr.fail(); + + bool bad(); + /// Returns _istr.bad(); + + bool eof(); + /// Returns _istr.eof(); + + std::istream& stream() const; + /// Returns the underlying stream. + + StreamByteOrder byteOrder() const; + /// Returns the byte-order used by the reader, which is + /// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER. + + void setExceptions(std::ios_base::iostate st = (std::istream::failbit | std::istream::badbit)); + /// Sets the stream to throw exception on specified state (default failbit and badbit); + + std::streamsize available() const; + /// Returns the number of available bytes in the stream. + +private: + std::istream& _istr; + bool _flipBytes; + TextConverter* _pTextConverter; +}; + + +template <typename T> +class BasicMemoryBinaryReader : public BinaryReader + /// A convenient wrapper for using Buffer and MemoryStream with BinaryReader. +{ +public: + BasicMemoryBinaryReader(const Buffer<T>& dataBuffer, StreamByteOrder order = NATIVE_BYTE_ORDER): + BinaryReader(_istr, order), + _data(dataBuffer), + _istr(dataBuffer.begin(), dataBuffer.capacity()) + { + } + + BasicMemoryBinaryReader(const Buffer<T>& dataBuffer, TextEncoding& encoding, StreamByteOrder order = NATIVE_BYTE_ORDER): + BinaryReader(_istr, encoding, order), + _data(dataBuffer), + _istr(dataBuffer.begin(), dataBuffer.capacity()) + { + } + + ~BasicMemoryBinaryReader() + { + } + + const Buffer<T>& data() const + { + return _data; + } + + const MemoryInputStream& stream() const + { + return _istr; + } + + MemoryInputStream& stream() + { + return _istr; + } + +private: + const Buffer<T>& _data; + MemoryInputStream _istr; +}; + + +typedef BasicMemoryBinaryReader<char> MemoryBinaryReader; + + +// +// inlines +// + + +inline bool BinaryReader::good() +{ + return _istr.good(); +} + + +inline bool BinaryReader::fail() +{ + return _istr.fail(); +} + + +inline bool BinaryReader::bad() +{ + return _istr.bad(); +} + + +inline bool BinaryReader::eof() +{ + return _istr.eof(); +} + + +inline std::istream& BinaryReader::stream() const +{ + return _istr; +} + + +inline BinaryReader::StreamByteOrder BinaryReader::byteOrder() const +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER; +#else + return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER; +#endif +} + + +inline void BinaryReader::setExceptions(std::ios_base::iostate st) +{ + _istr.exceptions(st); +} + + +inline std::streamsize BinaryReader::available() const +{ + return _istr.rdbuf()->in_avail(); +} + + +} // namespace Poco + + +#endif // Foundation_BinaryReader_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/BinaryWriter.h b/contrib/libs/poco/Foundation/include/Poco/BinaryWriter.h new file mode 100644 index 0000000000..2f71ef2f44 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/BinaryWriter.h @@ -0,0 +1,269 @@ +// +// BinaryWriter.h +// +// Library: Foundation +// Package: Streams +// Module: BinaryReaderWriter +// +// Definition of the BinaryWriter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_BinaryWriter_INCLUDED +#define Foundation_BinaryWriter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Buffer.h" +#include "Poco/MemoryStream.h" +#include <vector> +#include <ostream> + + +namespace Poco { + + +class TextEncoding; +class TextConverter; + + +class Foundation_API BinaryWriter + /// This class writes basic types (and std::vectors of these) + /// in binary form into an output stream. + /// It provides an inserter-based interface similar to ostream. + /// The writer also supports automatic conversion from big-endian + /// (network byte order) to little-endian and vice-versa. + /// Use a BinaryReader to read from a stream created by a BinaryWriter. + /// Be careful when exchanging data between systems with different + /// data type sizes (e.g., 32-bit and 64-bit architectures), as the sizes + /// of some of the basic types may be different. For example, writing a + /// long integer on a 64-bit system and reading it on a 32-bit system + /// may yield an incorrent result. Use fixed-size types (Int32, Int64, etc.) + /// in such a case. +{ +public: + enum StreamByteOrder + { + NATIVE_BYTE_ORDER = 1, /// the host's native byte-order + BIG_ENDIAN_BYTE_ORDER = 2, /// big-endian (network) byte-order + NETWORK_BYTE_ORDER = 2, /// big-endian (network) byte-order + LITTLE_ENDIAN_BYTE_ORDER = 3 /// little-endian byte-order + }; + + BinaryWriter(std::ostream& ostr, StreamByteOrder order = NATIVE_BYTE_ORDER); + /// Creates the BinaryWriter. + + BinaryWriter(std::ostream& ostr, TextEncoding& encoding, StreamByteOrder order = NATIVE_BYTE_ORDER); + /// Creates the BinaryWriter using the given TextEncoding. + /// + /// Strings will be converted from the currently set global encoding + /// (see Poco::TextEncoding::global()) to the specified encoding. + + ~BinaryWriter(); + /// Destroys the BinaryWriter. + + BinaryWriter& operator << (bool value); + BinaryWriter& operator << (char value); + BinaryWriter& operator << (unsigned char value); + BinaryWriter& operator << (signed char value); + BinaryWriter& operator << (short value); + BinaryWriter& operator << (unsigned short value); + BinaryWriter& operator << (int value); + BinaryWriter& operator << (unsigned int value); + BinaryWriter& operator << (long value); + BinaryWriter& operator << (unsigned long value); + BinaryWriter& operator << (float value); + BinaryWriter& operator << (double value); + +#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + BinaryWriter& operator << (Int64 value); + BinaryWriter& operator << (UInt64 value); +#endif + + BinaryWriter& operator << (const std::string& value); + BinaryWriter& operator << (const char* value); + + template <typename T> + BinaryWriter& operator << (const std::vector<T>& value) + { + Poco::UInt32 size(static_cast<Poco::UInt32>(value.size())); + + *this << size; + for (typename std::vector<T>::const_iterator it = value.begin(); it != value.end(); ++it) + { + *this << *it; + } + + return *this; + } + + void write7BitEncoded(UInt32 value); + /// Writes a 32-bit unsigned integer in a compressed format. + /// The value is written out seven bits at a time, starting + /// with the seven least-significant bits. + /// The high bit of a byte indicates whether there are more bytes to be + /// written after this one. + /// If value will fit in seven bits, it takes only one byte of space. + /// If value will not fit in seven bits, the high bit is set on the first byte and + /// written out. value is then shifted by seven bits and the next byte is written. + /// This process is repeated until the entire integer has been written. + +#if defined(POCO_HAVE_INT64) + void write7BitEncoded(UInt64 value); + /// Writes a 64-bit unsigned integer in a compressed format. + /// The value written out seven bits at a time, starting + /// with the seven least-significant bits. + /// The high bit of a byte indicates whether there are more bytes to be + /// written after this one. + /// If value will fit in seven bits, it takes only one byte of space. + /// If value will not fit in seven bits, the high bit is set on the first byte and + /// written out. value is then shifted by seven bits and the next byte is written. + /// This process is repeated until the entire integer has been written. +#endif + + void writeRaw(const std::string& rawData); + /// Writes the string as-is to the stream. + + void writeRaw(const char* buffer, std::streamsize length); + /// Writes length raw bytes from the given buffer to the stream. + + void writeBOM(); + /// Writes a byte-order mark to the stream. A byte order mark is + /// a 16-bit integer with a value of 0xFEFF, written in host byte-order. + /// A BinaryReader uses the byte-order mark to determine the byte-order + /// of the stream. + + void flush(); + /// Flushes the underlying stream. + + bool good(); + /// Returns _ostr.good(); + + bool fail(); + /// Returns _ostr.fail(); + + bool bad(); + /// Returns _ostr.bad(); + + std::ostream& stream() const; + /// Returns the underlying stream. + + StreamByteOrder byteOrder() const; + /// Returns the byte ordering used by the writer, which is + /// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER. + +private: + std::ostream& _ostr; + bool _flipBytes; + TextConverter* _pTextConverter; +}; + + +template <typename T> +class BasicMemoryBinaryWriter: public BinaryWriter + /// A convenient wrapper for using Buffer and MemoryStream with BinarWriter. +{ +public: + BasicMemoryBinaryWriter(Buffer<T>& dataBuffer, StreamByteOrder order = NATIVE_BYTE_ORDER): + BinaryWriter(_ostr, order), + _data(dataBuffer), + _ostr(dataBuffer.begin(), dataBuffer.capacity()) + { + } + + BasicMemoryBinaryWriter(Buffer<T>& dataBuffer, TextEncoding& encoding, StreamByteOrder order = NATIVE_BYTE_ORDER): + BinaryWriter(_ostr, encoding, order), + _data(dataBuffer), + _ostr(dataBuffer.begin(), dataBuffer.capacity()) + { + } + + ~BasicMemoryBinaryWriter() + { + try + { + flush(); + } + catch (...) + { + poco_unexpected(); + } + } + + Buffer<T>& data() + { + return _data; + } + + const Buffer<T>& data() const + { + return _data; + } + + const MemoryOutputStream& stream() const + { + return _ostr; + } + + MemoryOutputStream& stream() + { + return _ostr; + } + +private: + Buffer<T>& _data; + MemoryOutputStream _ostr; +}; + + +typedef BasicMemoryBinaryWriter<char> MemoryBinaryWriter; + + +// +// inlines +// + + +inline std::ostream& BinaryWriter::stream() const +{ + return _ostr; +} + + +inline bool BinaryWriter::good() +{ + return _ostr.good(); +} + + +inline bool BinaryWriter::fail() +{ + return _ostr.fail(); +} + + +inline bool BinaryWriter::bad() +{ + return _ostr.bad(); +} + + +inline BinaryWriter::StreamByteOrder BinaryWriter::byteOrder() const +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER; +#else + return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER; +#endif +} + + +} // namespace Poco + + +#endif // Foundation_BinaryWriter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Buffer.h b/contrib/libs/poco/Foundation/include/Poco/Buffer.h new file mode 100644 index 0000000000..7305a83c4a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Buffer.h @@ -0,0 +1,329 @@ +// +// Buffer.h +// +// Library: Foundation +// Package: Core +// Module: Buffer +// +// Definition of the Buffer class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Buffer_INCLUDED +#define Foundation_Buffer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <cstring> +#include <cstddef> + + +namespace Poco { + + +template <class T> +class Buffer + /// A buffer class that allocates a buffer of a given type and size + /// in the constructor and deallocates the buffer in the destructor. + /// + /// This class is useful everywhere where a temporary buffer + /// is needed. +{ +public: + Buffer(std::size_t length): + _capacity(length), + _used(length), + _ptr(0), + _ownMem(true) + /// Creates and allocates the Buffer. + { + if (length > 0) + { + _ptr = new T[length]; + } + } + + Buffer(T* pMem, std::size_t length): + _capacity(length), + _used(length), + _ptr(pMem), + _ownMem(false) + /// Creates the Buffer. Length argument specifies the length + /// of the supplied memory pointed to by pMem in the number + /// of elements of type T. Supplied pointer is considered + /// blank and not owned by Buffer, so in this case Buffer + /// only acts as a wrapper around externally supplied + /// (and lifetime-managed) memory. + { + } + + Buffer(const T* pMem, std::size_t length): + _capacity(length), + _used(length), + _ptr(0), + _ownMem(true) + /// Creates and allocates the Buffer; copies the contents of + /// the supplied memory into the buffer. Length argument specifies + /// the length of the supplied memory pointed to by pMem in the + /// number of elements of type T. + { + if (_capacity > 0) + { + _ptr = new T[_capacity]; + std::memcpy(_ptr, pMem, _used * sizeof(T)); + } + } + + Buffer(const Buffer& other): + /// Copy constructor. + _capacity(other._used), + _used(other._used), + _ptr(0), + _ownMem(true) + { + if (_used) + { + _ptr = new T[_used]; + std::memcpy(_ptr, other._ptr, _used * sizeof(T)); + } + } + + Buffer& operator = (const Buffer& other) + /// Assignment operator. + { + if (this != &other) + { + Buffer tmp(other); + swap(tmp); + } + + return *this; + } + + ~Buffer() + /// Destroys the Buffer. + { + if (_ownMem) delete [] _ptr; + } + + void resize(std::size_t newCapacity, bool preserveContent = true) + /// Resizes the buffer capacity and size. If preserveContent is true, + /// the content of the old buffer is copied over to the + /// new buffer. The new capacity can be larger or smaller than + /// the current one; if it is smaller, capacity will remain intact. + /// Size will always be set to the new capacity. + /// + /// Buffers only wrapping externally owned storage can not be + /// resized. If resize is attempted on those, IllegalAccessException + /// is thrown. + { + if (!_ownMem) throw Poco::InvalidAccessException("Cannot resize buffer which does not own its storage."); + + if (newCapacity > _capacity) + { + T* ptr = new T[newCapacity]; + if (preserveContent) + { + std::memcpy(ptr, _ptr, _used * sizeof(T)); + } + delete [] _ptr; + _ptr = ptr; + _capacity = newCapacity; + } + + _used = newCapacity; + } + + void setCapacity(std::size_t newCapacity, bool preserveContent = true) + /// Sets the buffer capacity. If preserveContent is true, + /// the content of the old buffer is copied over to the + /// new buffer. The new capacity can be larger or smaller than + /// the current one; size will be set to the new capacity only if + /// new capacity is smaller than the current size, otherwise it will + /// remain intact. + /// + /// Buffers only wrapping externally owned storage can not be + /// resized. If resize is attempted on those, IllegalAccessException + /// is thrown. + { + if (!_ownMem) throw Poco::InvalidAccessException("Cannot resize buffer which does not own its storage."); + + if (newCapacity != _capacity) + { + T* ptr = 0; + if (newCapacity > 0) + { + ptr = new T[newCapacity]; + if (preserveContent) + { + std::size_t newSz = _used < newCapacity ? _used : newCapacity; + std::memcpy(ptr, _ptr, newSz * sizeof(T)); + } + } + delete [] _ptr; + _ptr = ptr; + _capacity = newCapacity; + + if (newCapacity < _used) _used = newCapacity; + } + } + + void assign(const T* buf, std::size_t sz) + /// Assigns the argument buffer to this buffer. + /// If necessary, resizes the buffer. + { + if (0 == sz) return; + if (sz > _capacity) resize(sz, false); + std::memcpy(_ptr, buf, sz * sizeof(T)); + _used = sz; + } + + void append(const T* buf, std::size_t sz) + /// Resizes this buffer and appends the argument buffer. + { + if (0 == sz) return; + resize(_used + sz, true); + std::memcpy(_ptr + _used - sz, buf, sz * sizeof(T)); + } + + void append(T val) + /// Resizes this buffer by one element and appends the argument value. + { + resize(_used + 1, true); + _ptr[_used - 1] = val; + } + + void append(const Buffer& buf) + /// Resizes this buffer and appends the argument buffer. + { + append(buf.begin(), buf.size()); + } + + std::size_t capacity() const + /// Returns the allocated memory size in elements. + { + return _capacity; + } + + std::size_t capacityBytes() const + /// Returns the allocated memory size in bytes. + { + return _capacity * sizeof(T); + } + + void swap(Buffer& other) + /// Swaps the buffer with another one. + { + using std::swap; + + swap(_ptr, other._ptr); + swap(_capacity, other._capacity); + swap(_used, other._used); + } + + bool operator == (const Buffer& other) const + /// Compare operator. + { + if (this != &other) + { + if (_used == other._used) + { + if (std::memcmp(_ptr, other._ptr, _used * sizeof(T)) == 0) + { + return true; + } + } + return false; + } + + return true; + } + + bool operator != (const Buffer& other) const + /// Compare operator. + { + return !(*this == other); + } + + void clear() + /// Sets the contents of the buffer to zero. + { + std::memset(_ptr, 0, _used * sizeof(T)); + } + + std::size_t size() const + /// Returns the used size of the buffer in elements. + { + return _used; + } + + std::size_t sizeBytes() const + /// Returns the used size of the buffer in bytes. + { + return _used * sizeof(T); + } + + T* begin() + /// Returns a pointer to the beginning of the buffer. + { + return _ptr; + } + + const T* begin() const + /// Returns a pointer to the beginning of the buffer. + { + return _ptr; + } + + T* end() + /// Returns a pointer to end of the buffer. + { + return _ptr + _used; + } + + const T* end() const + /// Returns a pointer to the end of the buffer. + { + return _ptr + _used; + } + + bool empty() const + /// Return true if buffer is empty. + { + return 0 == _used; + } + + T& operator [] (std::size_t index) + { + poco_assert (index < _used); + + return _ptr[index]; + } + + const T& operator [] (std::size_t index) const + { + poco_assert (index < _used); + + return _ptr[index]; + } + +private: + Buffer(); + + std::size_t _capacity; + std::size_t _used; + T* _ptr; + bool _ownMem; +}; + + +} // namespace Poco + + +#endif // Foundation_Buffer_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/BufferAllocator.h b/contrib/libs/poco/Foundation/include/Poco/BufferAllocator.h new file mode 100644 index 0000000000..c767fe4ad7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/BufferAllocator.h @@ -0,0 +1,52 @@ +// +// BufferAllocator.h +// +// Library: Foundation +// Package: Streams +// Module: BufferAllocator +// +// Definition of the BufferAllocator class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_BufferAllocator_INCLUDED +#define Foundation_BufferAllocator_INCLUDED + + +#include "Poco/Foundation.h" +#include <ios> +#include <cstddef> + + +namespace Poco { + + +template <typename ch> +class BufferAllocator + /// The BufferAllocator used if no specific + /// BufferAllocator has been specified. +{ +public: + typedef ch char_type; + + static char_type* allocate(std::streamsize size) + { + return new char_type[static_cast<std::size_t>(size)]; + } + + static void deallocate(char_type* ptr, std::streamsize /*size*/) noexcept + { + delete [] ptr; + } +}; + + +} // namespace Poco + + +#endif // Foundation_BufferAllocator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h b/contrib/libs/poco/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h new file mode 100644 index 0000000000..321c3b1adb --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h @@ -0,0 +1,181 @@ +// +// BufferedBidirectionalStreamBuf.h +// +// Library: Foundation +// Package: Streams +// Module: StreamBuf +// +// Definition of template BasicBufferedBidirectionalStreamBuf and class BufferedBidirectionalStreamBuf. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_BufferedBidirectionalStreamBuf_INCLUDED +#define Foundation_BufferedBidirectionalStreamBuf_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferAllocator.h" +#include "Poco/StreamUtil.h" +#include <streambuf> +#include <iosfwd> +#include <ios> + + +namespace Poco { + + +template <typename ch, typename tr, typename ba = BufferAllocator<ch> > +class BasicBufferedBidirectionalStreamBuf: public std::basic_streambuf<ch, tr> + /// This is an implementation of a buffered bidirectional + /// streambuf that greatly simplifies the implementation of + /// custom streambufs of various kinds. + /// Derived classes only have to override the methods + /// readFromDevice() or writeToDevice(). + /// + /// In contrast to BasicBufferedStreambuf, this class supports + /// simultaneous read and write access, so in addition to + /// istream and ostream this streambuf can also be used + /// for implementing an iostream. +{ +protected: + typedef std::basic_streambuf<ch, tr> Base; + typedef std::basic_ios<ch, tr> IOS; + typedef ch char_type; + typedef tr char_traits; + typedef ba Allocator; + typedef typename Base::int_type int_type; + typedef typename Base::pos_type pos_type; + typedef typename Base::off_type off_type; + typedef typename IOS::openmode openmode; + +public: + BasicBufferedBidirectionalStreamBuf(std::streamsize bufferSize, openmode mode): + _bufsize(bufferSize), + _pReadBuffer(Allocator::allocate(_bufsize)), + _pWriteBuffer(Allocator::allocate(_bufsize)), + _mode(mode) + { + resetBuffers(); + } + + ~BasicBufferedBidirectionalStreamBuf() + { + Allocator::deallocate(_pReadBuffer, _bufsize); + Allocator::deallocate(_pWriteBuffer, _bufsize); + } + + virtual int_type overflow(int_type c) + { + if (!(_mode & IOS::out)) return char_traits::eof(); + + if (flushBuffer() == std::streamsize(-1)) return char_traits::eof(); + if (c != char_traits::eof()) + { + *this->pptr() = char_traits::to_char_type(c); + this->pbump(1); + } + + return c; + } + + virtual int_type underflow() + { + if (!(_mode & IOS::in)) return char_traits::eof(); + + if (this->gptr() && (this->gptr() < this->egptr())) + return char_traits::to_int_type(*this->gptr()); + + int putback = int(this->gptr() - this->eback()); + if (putback > 4) putback = 4; + + char_traits::move(_pReadBuffer + (4 - putback), this->gptr() - putback, putback); + + int n = readFromDevice(_pReadBuffer + 4, _bufsize - 4); + if (n <= 0) return char_traits::eof(); + + this->setg(_pReadBuffer + (4 - putback), _pReadBuffer + 4, _pReadBuffer + 4 + n); + + // return next character + return char_traits::to_int_type(*this->gptr()); + } + + virtual int sync() + { + if (this->pptr() && this->pptr() > this->pbase()) + { + if (flushBuffer() == -1) return -1; + } + return 0; + } + +protected: + void setMode(openmode mode) + { + _mode = mode; + } + + openmode getMode() const + { + return _mode; + } + + void resetBuffers() + { + this->setg(_pReadBuffer + 4, _pReadBuffer + 4, _pReadBuffer + 4); + this->setp(_pWriteBuffer, _pWriteBuffer + _bufsize); + } + +private: + virtual int readFromDevice(char_type* /*buffer*/, std::streamsize /*length*/) + { + return 0; + } + + virtual int writeToDevice(const char_type* /*buffer*/, std::streamsize /*length*/) + { + return 0; + } + + int flushBuffer() + { + int n = int(this->pptr() - this->pbase()); + if (writeToDevice(this->pbase(), n) == n) + { + this->pbump(-n); + return n; + } + return -1; + } + + std::streamsize _bufsize; + char_type* _pReadBuffer; + char_type* _pWriteBuffer; + openmode _mode; + + BasicBufferedBidirectionalStreamBuf(const BasicBufferedBidirectionalStreamBuf&); + BasicBufferedBidirectionalStreamBuf& operator = (const BasicBufferedBidirectionalStreamBuf&); +}; + + +// +// We provide an instantiation for char. +// +// Visual C++ needs a workaround - explicitly importing the template +// instantiation - to avoid duplicate symbols due to multiple +// instantiations in different libraries. +// +#if defined(_MSC_VER) && defined(POCO_DLL) && !defined(Foundation_EXPORTS) +template class Foundation_API BasicBufferedBidirectionalStreamBuf<char, std::char_traits<char> >; +#endif +typedef BasicBufferedBidirectionalStreamBuf<char, std::char_traits<char> > BufferedBidirectionalStreamBuf; + + +} // namespace Poco + + +#endif // Foundation_BufferedBidirectionalStreamBuf_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/BufferedStreamBuf.h b/contrib/libs/poco/Foundation/include/Poco/BufferedStreamBuf.h new file mode 100644 index 0000000000..3e39215262 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/BufferedStreamBuf.h @@ -0,0 +1,173 @@ +// +// BufferedStreamBuf.h +// +// Library: Foundation +// Package: Streams +// Module: StreamBuf +// +// Definition of template BasicBufferedStreamBuf and class BufferedStreamBuf. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_BufferedStreamBuf_INCLUDED +#define Foundation_BufferedStreamBuf_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferAllocator.h" +#include "Poco/StreamUtil.h" +#include <streambuf> +#include <iosfwd> +#include <ios> + + +namespace Poco { + + +template <typename ch, typename tr, typename ba = BufferAllocator<ch> > +class BasicBufferedStreamBuf: public std::basic_streambuf<ch, tr> + /// This is an implementation of a buffered streambuf + /// that greatly simplifies the implementation of + /// custom streambufs of various kinds. + /// Derived classes only have to override the methods + /// readFromDevice() or writeToDevice(). + /// + /// This streambuf only supports unidirectional streams. + /// In other words, the BasicBufferedStreamBuf can be + /// used for the implementation of an istream or an + /// ostream, but not for an iostream. +{ +protected: + typedef std::basic_streambuf<ch, tr> Base; + typedef std::basic_ios<ch, tr> IOS; + typedef ch char_type; + typedef tr char_traits; + typedef ba Allocator; + typedef typename Base::int_type int_type; + typedef typename Base::pos_type pos_type; + typedef typename Base::off_type off_type; + typedef typename IOS::openmode openmode; + +public: + BasicBufferedStreamBuf(std::streamsize bufferSize, openmode mode): + _bufsize(bufferSize), + _pBuffer(Allocator::allocate(_bufsize)), + _mode(mode) + { + this->setg(_pBuffer + 4, _pBuffer + 4, _pBuffer + 4); + this->setp(_pBuffer, _pBuffer + _bufsize); + } + + ~BasicBufferedStreamBuf() + { + Allocator::deallocate(_pBuffer, _bufsize); + } + + virtual int_type overflow(int_type c) + { + if (!(_mode & IOS::out)) return char_traits::eof(); + + if (flushBuffer() == std::streamsize(-1)) return char_traits::eof(); + if (c != char_traits::eof()) + { + *this->pptr() = char_traits::to_char_type(c); + this->pbump(1); + } + + return c; + } + + virtual int_type underflow() + { + if (!(_mode & IOS::in)) return char_traits::eof(); + + if (this->gptr() && (this->gptr() < this->egptr())) + return char_traits::to_int_type(*this->gptr()); + + int putback = int(this->gptr() - this->eback()); + if (putback > 4) putback = 4; + + char_traits::move(_pBuffer + (4 - putback), this->gptr() - putback, putback); + + int n = readFromDevice(_pBuffer + 4, _bufsize - 4); + if (n <= 0) return char_traits::eof(); + + this->setg(_pBuffer + (4 - putback), _pBuffer + 4, _pBuffer + 4 + n); + + // return next character + return char_traits::to_int_type(*this->gptr()); + } + + virtual int sync() + { + if (this->pptr() && this->pptr() > this->pbase()) + { + if (flushBuffer() == -1) return -1; + } + return 0; + } + +protected: + void setMode(openmode mode) + { + _mode = mode; + } + + openmode getMode() const + { + return _mode; + } + +private: + virtual int readFromDevice(char_type* /*buffer*/, std::streamsize /*length*/) + { + return 0; + } + + virtual int writeToDevice(const char_type* /*buffer*/, std::streamsize /*length*/) + { + return 0; + } + + int flushBuffer() + { + int n = int(this->pptr() - this->pbase()); + if (writeToDevice(this->pbase(), n) == n) + { + this->pbump(-n); + return n; + } + return -1; + } + + std::streamsize _bufsize; + char_type* _pBuffer; + openmode _mode; + + BasicBufferedStreamBuf(const BasicBufferedStreamBuf&); + BasicBufferedStreamBuf& operator = (const BasicBufferedStreamBuf&); +}; + + +// +// We provide an instantiation for char. +// +// Visual C++ needs a workaround - explicitly importing the template +// instantiation - to avoid duplicate symbols due to multiple +// instantiations in different libraries. +// +#if defined(_MSC_VER) && defined(POCO_DLL) && !defined(Foundation_EXPORTS) +template class Foundation_API BasicBufferedStreamBuf<char, std::char_traits<char> >; +#endif +typedef BasicBufferedStreamBuf<char, std::char_traits<char> > BufferedStreamBuf; + + +} // namespace Poco + + +#endif // Foundation_BufferedStreamBuf_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Bugcheck.h b/contrib/libs/poco/Foundation/include/Poco/Bugcheck.h new file mode 100644 index 0000000000..e97cd7cd80 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Bugcheck.h @@ -0,0 +1,207 @@ +// +// Bugcheck.h +// +// Library: Foundation +// Package: Core +// Module: Bugcheck +// +// Definition of the Bugcheck class and the self-testing macros. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Bugcheck_INCLUDED +#define Foundation_Bugcheck_INCLUDED + + +#include "Poco/Foundation.h" +#include <string> +#include <cstdlib> +#if defined(_DEBUG) +# include <iostream> +#endif + + +namespace Poco { + + +class Foundation_API Bugcheck + /// This class provides some static methods that are + /// used by the + /// poco_assert_dbg(), poco_assert(), poco_check_ptr(), + /// poco_bugcheck() and poco_unexpected() macros. + /// You should not invoke these methods + /// directly. Use the macros instead, as they + /// automatically provide useful context information. +{ +public: + static void assertion(const char* cond, const char* file, int line, const char* text = 0); + /// An assertion failed. Break into the debugger, if + /// possible, then throw an AssertionViolationException. + + static void nullPointer(const char* ptr, const char* file, int line); + /// An null pointer was encountered. Break into the debugger, if + /// possible, then throw an NullPointerException. + + static void bugcheck(const char* file, int line); + /// An internal error was encountered. Break into the debugger, if + /// possible, then throw an BugcheckException. + + static void bugcheck(const char* msg, const char* file, int line); + /// An internal error was encountered. Break into the debugger, if + /// possible, then throw an BugcheckException. + + static void unexpected(const char* file, int line); + /// An exception was caught in a destructor. Break into debugger, + /// if possible and report exception. Must only be called from + /// within a catch () block as it rethrows the exception to + /// determine its class. + + static void debugger(const char* file, int line); + /// An internal error was encountered. Break into the debugger, if + /// possible. + + static void debugger(const char* msg, const char* file, int line); + /// An internal error was encountered. Break into the debugger, if + /// possible. + +protected: + static std::string what(const char* msg, const char* file, int line, const char* text = 0); +}; + + +} // namespace Poco + + +// +// useful macros (these automatically supply line number and file name) +// +#if defined(__KLOCWORK__) || defined(__clang_analyzer__) + + +// Short-circuit these macros when under static analysis. +// Ideally, static analysis tools should understand and reason correctly about +// noreturn methods such as Bugcheck::bugcheck(). In practice, they don't. +// Help them by turning these macros into std::abort() as described here: +// https://developer.klocwork.com/documentation/en/insight/10-1/tuning-cc-analysis#Usingthe__KLOCWORK__macro + +#include <cstdlib> // for abort +#define poco_assert_dbg(cond) do { if (!(cond)) std::abort(); } while (0) +#define poco_assert_msg_dbg(cond, text) do { if (!(cond)) std::abort(); } while (0) +#define poco_assert(cond) do { if (!(cond)) std::abort(); } while (0) +#define poco_assert_msg(cond, text) do { if (!(cond)) std::abort(); } while (0) +#define poco_check_ptr(ptr) do { if (!(ptr)) std::abort(); } while (0) +#define poco_bugcheck() do { std::abort(); } while (0) +#define poco_bugcheck_msg(msg) do { std::abort(); } while (0) + + +#else // defined(__KLOCWORK__) || defined(__clang_analyzer__) + + +#if defined(_DEBUG) + #define poco_assert_dbg(cond) \ + if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0 + + #define poco_assert_msg_dbg(cond, text) \ + if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__, text); else (void) 0 +#else + #define poco_assert_msg_dbg(cond, text) + #define poco_assert_dbg(cond) +#endif + + +#define poco_assert(cond) \ + if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0 + + +#define poco_assert_msg(cond, text) \ + if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__, text); else (void) 0 + + +#define poco_check_ptr(ptr) \ + if (!(ptr)) Poco::Bugcheck::nullPointer(#ptr, __FILE__, __LINE__); else (void) 0 + + +#define poco_bugcheck() \ + Poco::Bugcheck::bugcheck(__FILE__, __LINE__) + + +#define poco_bugcheck_msg(msg) \ + Poco::Bugcheck::bugcheck(msg, __FILE__, __LINE__) + + +#endif // defined(__KLOCWORK__) || defined(__clang_analyzer__) + + +#define poco_unexpected() \ + Poco::Bugcheck::unexpected(__FILE__, __LINE__); + + +#define poco_debugger() \ + Poco::Bugcheck::debugger(__FILE__, __LINE__) + + +#define poco_debugger_msg(msg) \ + Poco::Bugcheck::debugger(msg, __FILE__, __LINE__) + + +#if defined(_DEBUG) +# define poco_stdout_dbg(outstr) \ + std::cout << __FILE__ << '(' << std::dec << __LINE__ << "):" << outstr << std::endl; +#else +# define poco_stdout_dbg(outstr) +#endif + + +#if defined(_DEBUG) +# define poco_stderr_dbg(outstr) \ + std::cerr << __FILE__ << '(' << std::dec << __LINE__ << "):" << outstr << std::endl; +#else +# define poco_stderr_dbg(outstr) +#endif + + +// +// poco_static_assert +// +// The following was ported from <boost/static_assert.hpp> +// + + +template <bool x> +struct POCO_STATIC_ASSERTION_FAILURE +{ +}; + +template <> +struct POCO_STATIC_ASSERTION_FAILURE<true> +{ + enum + { + value = 1 + }; +}; + + +template <int x> +struct poco_static_assert_test +{ +}; + + +#if defined(__GNUC__) && (__GNUC__ == 3) && ((__GNUC_MINOR__ == 3) || (__GNUC_MINOR__ == 4)) +#define poco_static_assert(B) \ + typedef char POCO_JOIN(poco_static_assert_typedef_, __LINE__) \ + [POCO_STATIC_ASSERTION_FAILURE<(bool) (B)>::value] +#else +#define poco_static_assert(B) \ + typedef poco_static_assert_test<sizeof(POCO_STATIC_ASSERTION_FAILURE<(bool) (B)>)> \ + POCO_JOIN(poco_static_assert_typedef_, __LINE__) POCO_UNUSED +#endif + + +#endif // Foundation_Bugcheck_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ByteOrder.h b/contrib/libs/poco/Foundation/include/Poco/ByteOrder.h new file mode 100644 index 0000000000..97732bcd49 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ByteOrder.h @@ -0,0 +1,239 @@ +// +// ByteOrder.h +// +// Library: Foundation +// Package: Core +// Module: ByteOrder +// +// Copyright (c) 2004-2014, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ByteOrder_INCLUDED +#define Foundation_ByteOrder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Types.h" +#if defined(_MSC_VER) +#include <stdlib.h> // builtins +#endif + + +namespace Poco { + + +class Foundation_API ByteOrder + /// This class contains a number of static methods + /// to convert between big-endian and little-endian + /// integers of various sizes. +{ +public: + static Int16 flipBytes(Int16 value); + static UInt16 flipBytes(UInt16 value); + static Int32 flipBytes(Int32 value); + static UInt32 flipBytes(UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 flipBytes(Int64 value); + static UInt64 flipBytes(UInt64 value); +#endif + + static Int16 toBigEndian(Int16 value); + static UInt16 toBigEndian (UInt16 value); + static Int32 toBigEndian(Int32 value); + static UInt32 toBigEndian (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 toBigEndian(Int64 value); + static UInt64 toBigEndian (UInt64 value); +#endif + + static Int16 fromBigEndian(Int16 value); + static UInt16 fromBigEndian (UInt16 value); + static Int32 fromBigEndian(Int32 value); + static UInt32 fromBigEndian (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 fromBigEndian(Int64 value); + static UInt64 fromBigEndian (UInt64 value); +#endif + + static Int16 toLittleEndian(Int16 value); + static UInt16 toLittleEndian (UInt16 value); + static Int32 toLittleEndian(Int32 value); + static UInt32 toLittleEndian (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 toLittleEndian(Int64 value); + static UInt64 toLittleEndian (UInt64 value); +#endif + + static Int16 fromLittleEndian(Int16 value); + static UInt16 fromLittleEndian (UInt16 value); + static Int32 fromLittleEndian(Int32 value); + static UInt32 fromLittleEndian (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 fromLittleEndian(Int64 value); + static UInt64 fromLittleEndian (UInt64 value); +#endif + + static Int16 toNetwork(Int16 value); + static UInt16 toNetwork (UInt16 value); + static Int32 toNetwork(Int32 value); + static UInt32 toNetwork (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 toNetwork(Int64 value); + static UInt64 toNetwork (UInt64 value); +#endif + + static Int16 fromNetwork(Int16 value); + static UInt16 fromNetwork (UInt16 value); + static Int32 fromNetwork(Int32 value); + static UInt32 fromNetwork (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 fromNetwork(Int64 value); + static UInt64 fromNetwork (UInt64 value); +#endif +}; + + +#if !defined(POCO_NO_BYTESWAP_BUILTINS) + #if defined(_MSC_VER) + #if (POCO_MSVC_VERSION > 71) + #define POCO_HAVE_MSC_BYTESWAP 1 + #endif + #elif defined(__clang__) + #if __has_builtin(__builtin_bswap32) + #define POCO_HAVE_GCC_BYTESWAP 1 + #endif + #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define POCO_HAVE_GCC_BYTESWAP 1 + #endif +#endif + + +// +// inlines +// +inline UInt16 ByteOrder::flipBytes(UInt16 value) +{ +#if defined(POCO_HAVE_MSC_BYTESWAP) + return _byteswap_ushort(value); +#else + return ((value >> 8) & 0x00FF) | ((value << 8) & 0xFF00); +#endif +} + + +inline Int16 ByteOrder::flipBytes(Int16 value) +{ + return Int16(flipBytes(UInt16(value))); +} + + +inline UInt32 ByteOrder::flipBytes(UInt32 value) +{ +#if defined(POCO_HAVE_MSC_BYTESWAP) + return _byteswap_ulong(value); +#elif defined(POCO_HAVE_GCC_BYTESWAP) + return __builtin_bswap32(value); +#else + return ((value >> 24) & 0x000000FF) | ((value >> 8) & 0x0000FF00) + | ((value << 8) & 0x00FF0000) | ((value << 24) & 0xFF000000); +#endif +} + + +inline Int32 ByteOrder::flipBytes(Int32 value) +{ + return Int32(flipBytes(UInt32(value))); +} + + +#if defined(POCO_HAVE_INT64) +inline UInt64 ByteOrder::flipBytes(UInt64 value) +{ +#if defined(POCO_HAVE_MSC_BYTESWAP) + return _byteswap_uint64(value); +#elif defined(POCO_HAVE_GCC_BYTESWAP) + return __builtin_bswap64(value); +#else + UInt32 hi = UInt32(value >> 32); + UInt32 lo = UInt32(value & 0xFFFFFFFF); + return UInt64(flipBytes(hi)) | (UInt64(flipBytes(lo)) << 32); +#endif +} + + +inline Int64 ByteOrder::flipBytes(Int64 value) +{ + return Int64(flipBytes(UInt64(value))); +} +#endif // POCO_HAVE_INT64 + + +// +// some macro trickery to automate the method implementation +// +#define POCO_IMPLEMENT_BYTEORDER_NOOP_(op, type) \ + inline type ByteOrder::op(type value) \ + { \ + return value; \ + } +#define POCO_IMPLEMENT_BYTEORDER_FLIP_(op, type) \ + inline type ByteOrder::op(type value) \ + { \ + return flipBytes(value); \ + } + + +#if defined(POCO_HAVE_INT64) + #define POCO_IMPLEMENT_BYTEORDER_NOOP(op) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int64) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt64) + #define POCO_IMPLEMENT_BYTEORDER_FLIP(op) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int64) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt64) +#else + #define POCO_IMPLEMENT_BYTEORDER_NOOP(op) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) + #define POCO_IMPLEMENT_BYTEORDER_FLIP(op) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) +#endif + + +#if defined(POCO_ARCH_BIG_ENDIAN) + #define POCO_IMPLEMENT_BYTEORDER_BIG POCO_IMPLEMENT_BYTEORDER_NOOP + #define POCO_IMPLEMENT_BYTEORDER_LIT POCO_IMPLEMENT_BYTEORDER_FLIP +#else + #define POCO_IMPLEMENT_BYTEORDER_BIG POCO_IMPLEMENT_BYTEORDER_FLIP + #define POCO_IMPLEMENT_BYTEORDER_LIT POCO_IMPLEMENT_BYTEORDER_NOOP +#endif + + +POCO_IMPLEMENT_BYTEORDER_BIG(toBigEndian) +POCO_IMPLEMENT_BYTEORDER_BIG(fromBigEndian) +POCO_IMPLEMENT_BYTEORDER_BIG(toNetwork) +POCO_IMPLEMENT_BYTEORDER_BIG(fromNetwork) +POCO_IMPLEMENT_BYTEORDER_LIT(toLittleEndian) +POCO_IMPLEMENT_BYTEORDER_LIT(fromLittleEndian) + + +} // namespace Poco + + +#endif // Foundation_ByteOrder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Channel.h b/contrib/libs/poco/Foundation/include/Poco/Channel.h new file mode 100644 index 0000000000..f820a2c3c7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Channel.h @@ -0,0 +1,78 @@ +// +// Channel.h +// +// Library: Foundation +// Package: Logging +// Module: Channel +// +// Definition of the Channel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Channel_INCLUDED +#define Foundation_Channel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Configurable.h" +#include "Poco/Mutex.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Message; + + +class Foundation_API Channel: public Configurable, public RefCountedObject + /// The base class for all Channel classes. + /// + /// Supports reference counting based garbage + /// collection and provides trivial implementations + /// of getProperty() and setProperty(). +{ +public: + Channel(); + /// Creates the channel and initializes + /// the reference count to one. + + virtual void open(); + /// Does whatever is necessary to open the channel. + /// The default implementation does nothing. + + virtual void close(); + /// Does whatever is necessary to close the channel. + /// The default implementation does nothing. + + virtual void log(const Message& msg) = 0; + /// Logs the given message to the channel. Must be + /// overridden by subclasses. + /// + /// If the channel has not been opened yet, the log() + /// method will open it. + + void setProperty(const std::string& name, const std::string& value); + /// Throws a PropertyNotSupportedException. + + std::string getProperty(const std::string& name) const; + /// Throws a PropertyNotSupportedException. + +protected: + virtual ~Channel(); + +private: + Channel(const Channel&); + Channel& operator = (const Channel&); +}; + + +} // namespace Poco + + +#endif // Foundation_Channel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Checksum.h b/contrib/libs/poco/Foundation/include/Poco/Checksum.h new file mode 100644 index 0000000000..3961bb762b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Checksum.h @@ -0,0 +1,108 @@ +// +// Checksum.h +// +// Library: Foundation +// Package: Core +// Module: Checksum +// +// Definition of the Checksum class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Checksum_INCLUDED +#define Foundation_Checksum_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Checksum + /// This class calculates CRC-32 or Adler-32 checksums + /// for arbitrary data. + /// + /// A cyclic redundancy check (CRC) is a type of hash function, which is used to produce a + /// small, fixed-size checksum of a larger block of data, such as a packet of network + /// traffic or a computer file. CRC-32 is one of the most commonly used CRC algorithms. + /// + /// Adler-32 is a checksum algorithm which was invented by Mark Adler. + /// It is almost as reliable as a 32-bit cyclic redundancy check for protecting against + /// accidental modification of data, such as distortions occurring during a transmission, + /// but is significantly faster to calculate in software. + +{ +public: + enum Type + { + TYPE_ADLER32 = 0, + TYPE_CRC32 + }; + + Checksum(); + /// Creates a CRC-32 checksum initialized to 0. + + Checksum(Type t); + /// Creates the Checksum, using the given type. + + ~Checksum(); + /// Destroys the Checksum. + + void update(const char* data, unsigned length); + /// Updates the checksum with the given data. + + void update(const std::string& data); + /// Updates the checksum with the given data. + + void update(char data); + /// Updates the checksum with the given data. + + Poco::UInt32 checksum() const; + /// Returns the calculated checksum. + + Type type() const; + /// Which type of checksum are we calulcating + +private: + Type _type; + Poco::UInt32 _value; +}; + + +// +// inlines +// +inline void Checksum::update(const std::string& data) +{ + update(data.c_str(), static_cast<unsigned int>(data.size())); +} + + +inline void Checksum::update(char c) +{ + update(&c, 1); +} + + +inline Poco::UInt32 Checksum::checksum() const +{ + return _value; +} + + +inline Checksum::Type Checksum::type() const +{ + return _type; +} + + +} // namespace Poco + + +#endif // Foundation_Checksum_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ClassLibrary.h b/contrib/libs/poco/Foundation/include/Poco/ClassLibrary.h new file mode 100644 index 0000000000..14b10acb3d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ClassLibrary.h @@ -0,0 +1,101 @@ +// +// ClassLibrary.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Definitions for class libraries. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ClassLibrary_INCLUDED +#define Foundation_ClassLibrary_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Manifest.h" +#include <typeinfo> + + +#if defined(_WIN32) + #define POCO_LIBRARY_API __declspec(dllexport) +#else + #define POCO_LIBRARY_API +#endif + + +// +// the entry points for every class library +// +extern "C" +{ + bool POCO_LIBRARY_API pocoBuildManifest(Poco::ManifestBase* pManifest); + void POCO_LIBRARY_API pocoInitializeLibrary(); + void POCO_LIBRARY_API pocoUninitializeLibrary(); +} + + +// +// additional support for named manifests +// +#define POCO_DECLARE_NAMED_MANIFEST(name) \ +extern "C" \ +{ \ + bool POCO_LIBRARY_API POCO_JOIN(pocoBuildManifest, name)(Poco::ManifestBase* pManifest); \ +} + + +// +// Macros to automatically implement pocoBuildManifest +// +// usage: +// +// POCO_BEGIN_MANIFEST(MyBaseClass) +// POCO_EXPORT_CLASS(MyFirstClass) +// POCO_EXPORT_CLASS(MySecondClass) +// ... +// POCO_END_MANIFEST +// +#define POCO_BEGIN_MANIFEST_IMPL(fnName, base) \ + bool fnName(Poco::ManifestBase* pManifest_) \ + { \ + typedef base _Base; \ + typedef Poco::Manifest<_Base> _Manifest; \ + std::string requiredType(typeid(_Manifest).name()); \ + std::string actualType(pManifest_->className()); \ + if (requiredType == actualType) \ + { \ + Poco::Manifest<_Base>* pManifest = static_cast<_Manifest*>(pManifest_); + + +#define POCO_BEGIN_MANIFEST(base) \ + POCO_BEGIN_MANIFEST_IMPL(pocoBuildManifest, base) + + +#define POCO_BEGIN_NAMED_MANIFEST(name, base) \ + POCO_DECLARE_NAMED_MANIFEST(name) \ + POCO_BEGIN_MANIFEST_IMPL(POCO_JOIN(pocoBuildManifest, name), base) + + +#define POCO_END_MANIFEST \ + return true; \ + } \ + else return false; \ + } + + +#define POCO_EXPORT_CLASS(cls) \ + pManifest->insert(new Poco::MetaObject<cls, _Base>(#cls)); + + +#define POCO_EXPORT_SINGLETON(cls) \ + pManifest->insert(new Poco::MetaSingleton<cls, _Base>(#cls)); + + +#endif // Foundation_ClassLibrary_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ClassLoader.h b/contrib/libs/poco/Foundation/include/Poco/ClassLoader.h new file mode 100644 index 0000000000..450aec2928 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ClassLoader.h @@ -0,0 +1,365 @@ +// +// ClassLoader.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Definition of the ClassLoader class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ClassLoader_INCLUDED +#define Foundation_ClassLoader_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/MetaObject.h" +#include "Poco/Manifest.h" +#include "Poco/SharedLibrary.h" +#include "Poco/Mutex.h" +#include "Poco/Exception.h" +#include <map> + + +namespace Poco { + + +template <class Base> +class ClassLoader + /// The ClassLoader loads C++ classes from shared libraries + /// at runtime. It must be instantiated with a root class + /// of the loadable classes. + /// For a class to be loadable from a library, the library + /// must provide a Manifest of all the classes it contains. + /// The Manifest for a shared library can be easily built + /// with the help of the macros in the header file + /// "Foundation/ClassLibrary.h". + /// + /// Starting with POCO release 1.3, a class library can + /// export multiple manifests. In addition to the default + /// (unnamed) manifest, multiple named manifests can + /// be exported, each having a different base class. + /// + /// There is one important restriction: one instance of + /// ClassLoader can only load one manifest from a class + /// library. +{ +public: + typedef AbstractMetaObject<Base> Meta; + typedef Manifest<Base> Manif; + typedef void (*InitializeLibraryFunc)(); + typedef void (*UninitializeLibraryFunc)(); + typedef bool (*BuildManifestFunc)(ManifestBase*); + + struct LibraryInfo + { + SharedLibrary* pLibrary; + const Manif* pManifest; + int refCount; + }; + typedef std::map<std::string, LibraryInfo> LibraryMap; + + class Iterator + /// The ClassLoader's very own iterator class. + { + public: + typedef std::pair<std::string, const Manif*> Pair; + + Iterator(const typename LibraryMap::const_iterator& it) + { + _it = it; + } + Iterator(const Iterator& it) + { + _it = it._it; + } + ~Iterator() + { + } + Iterator& operator = (const Iterator& it) + { + _it = it._it; + return *this; + } + inline bool operator == (const Iterator& it) const + { + return _it == it._it; + } + inline bool operator != (const Iterator& it) const + { + return _it != it._it; + } + Iterator& operator ++ () // prefix + { + ++_it; + return *this; + } + Iterator operator ++ (int) // postfix + { + Iterator result(_it); + ++_it; + return result; + } + inline const Pair* operator * () const + { + _pair.first = _it->first; + _pair.second = _it->second.pManifest; + return &_pair; + } + inline const Pair* operator -> () const + { + _pair.first = _it->first; + _pair.second = _it->second.pManifest; + return &_pair; + } + + private: + typename LibraryMap::const_iterator _it; + mutable Pair _pair; + }; + + ClassLoader() + /// Creates the ClassLoader. + { + } + + virtual ~ClassLoader() + /// Destroys the ClassLoader. + { + for (typename LibraryMap::const_iterator it = _map.begin(); it != _map.end(); ++it) + { + delete it->second.pLibrary; + delete it->second.pManifest; + } + } + + void loadLibrary(const std::string& path, const std::string& manifest) + /// Loads a library from the given path, using the given manifest. + /// Does nothing if the library is already loaded. + /// Throws a LibraryLoadException if the library + /// cannot be loaded or does not have a Manifest. + /// If the library exports a function named "pocoInitializeLibrary", + /// this function is executed. + /// If called multiple times for the same library, + /// the number of calls to unloadLibrary() must be the same + /// for the library to become unloaded. + { + FastMutex::ScopedLock lock(_mutex); + + typename LibraryMap::iterator it = _map.find(path); + if (it == _map.end()) + { + LibraryInfo li; + li.pLibrary = 0; + li.pManifest = 0; + li.refCount = 1; + try + { + li.pLibrary = new SharedLibrary(path); + li.pManifest = new Manif(); + std::string pocoBuildManifestSymbol("pocoBuildManifest"); + pocoBuildManifestSymbol.append(manifest); + if (li.pLibrary->hasSymbol("pocoInitializeLibrary")) + { + InitializeLibraryFunc initializeLibrary = (InitializeLibraryFunc) li.pLibrary->getSymbol("pocoInitializeLibrary"); + initializeLibrary(); + } + if (li.pLibrary->hasSymbol(pocoBuildManifestSymbol)) + { + BuildManifestFunc buildManifest = (BuildManifestFunc) li.pLibrary->getSymbol(pocoBuildManifestSymbol); + if (buildManifest(const_cast<Manif*>(li.pManifest))) + _map[path] = li; + else + throw LibraryLoadException(std::string("Manifest class mismatch in ") + path, manifest); + } + else throw LibraryLoadException(std::string("No manifest in ") + path, manifest); + } + catch (...) + { + delete li.pLibrary; + delete li.pManifest; + throw; + } + } + else + { + ++it->second.refCount; + } + } + + void loadLibrary(const std::string& path) + /// Loads a library from the given path. Does nothing + /// if the library is already loaded. + /// Throws a LibraryLoadException if the library + /// cannot be loaded or does not have a Manifest. + /// If the library exports a function named "pocoInitializeLibrary", + /// this function is executed. + /// If called multiple times for the same library, + /// the number of calls to unloadLibrary() must be the same + /// for the library to become unloaded. + /// + /// Equivalent to loadLibrary(path, ""). + { + loadLibrary(path, ""); + } + + void unloadLibrary(const std::string& path) + /// Unloads the given library. + /// Be extremely cautious when unloading shared libraries. + /// If objects from the library are still referenced somewhere, + /// a total crash is very likely. + /// If the library exports a function named "pocoUninitializeLibrary", + /// this function is executed before it is unloaded. + /// If loadLibrary() has been called multiple times for the same + /// library, the number of calls to unloadLibrary() must be the same + /// for the library to become unloaded. + { + FastMutex::ScopedLock lock(_mutex); + + typename LibraryMap::iterator it = _map.find(path); + if (it != _map.end()) + { + if (--it->second.refCount == 0) + { + if (it->second.pLibrary->hasSymbol("pocoUninitializeLibrary")) + { + UninitializeLibraryFunc uninitializeLibrary = (UninitializeLibraryFunc) it->second.pLibrary->getSymbol("pocoUninitializeLibrary"); + uninitializeLibrary(); + } + delete it->second.pManifest; + it->second.pLibrary->unload(); + delete it->second.pLibrary; + _map.erase(it); + } + } + else throw NotFoundException(path); + } + + const Meta* findClass(const std::string& className) const + /// Returns a pointer to the MetaObject for the given + /// class, or a null pointer if the class is not known. + { + FastMutex::ScopedLock lock(_mutex); + + for (typename LibraryMap::const_iterator it = _map.begin(); it != _map.end(); ++it) + { + const Manif* pManif = it->second.pManifest; + typename Manif::Iterator itm = pManif->find(className); + if (itm != pManif->end()) + return *itm; + } + return 0; + } + + const Meta& classFor(const std::string& className) const + /// Returns a reference to the MetaObject for the given + /// class. Throws a NotFoundException if the class + /// is not known. + { + const Meta* pMeta = findClass(className); + if (pMeta) + return *pMeta; + else + throw NotFoundException(className); + } + + Base* create(const std::string& className) const + /// Creates an instance of the given class. + /// Throws a NotFoundException if the class + /// is not known. + { + return classFor(className).create(); + } + + Base& instance(const std::string& className) const + /// Returns a reference to the sole instance of + /// the given class. The class must be a singleton, + /// otherwise an InvalidAccessException will be thrown. + /// Throws a NotFoundException if the class + /// is not known. + { + return classFor(className).instance(); + } + + bool canCreate(const std::string& className) const + /// Returns true if create() can create new instances + /// of the class. + { + return classFor(className).canCreate(); + } + + void destroy(const std::string& className, Base* pObject) const + /// Destroys the object pObject points to. + /// Does nothing if object is not found. + { + classFor(className).destroy(pObject); + } + + bool isAutoDelete(const std::string& className, Base* pObject) const + /// Returns true if the object is automatically + /// deleted by its meta object. + { + return classFor(className).isAutoDelete(pObject); + } + + const Manif* findManifest(const std::string& path) const + /// Returns a pointer to the Manifest for the given + /// library, or a null pointer if the library has not been loaded. + { + FastMutex::ScopedLock lock(_mutex); + + typename LibraryMap::const_iterator it = _map.find(path); + if (it != _map.end()) + return it->second.pManifest; + else + return 0; + } + + const Manif& manifestFor(const std::string& path) const + /// Returns a reference to the Manifest for the given library + /// Throws a NotFoundException if the library has not been loaded. + { + const Manif* pManif = findManifest(path); + if (pManif) + return *pManif; + else + throw NotFoundException(path); + } + + bool isLibraryLoaded(const std::string& path) const + /// Returns true if the library with the given name + /// has already been loaded. + { + return findManifest(path) != 0; + } + + Iterator begin() const + { + FastMutex::ScopedLock lock(_mutex); + + return Iterator(_map.begin()); + } + + Iterator end() const + { + FastMutex::ScopedLock lock(_mutex); + + return Iterator(_map.end()); + } + +private: + LibraryMap _map; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_ClassLoader_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Clock.h b/contrib/libs/poco/Foundation/include/Poco/Clock.h new file mode 100644 index 0000000000..43bb22f640 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Clock.h @@ -0,0 +1,238 @@ +// +// Clock.h +// +// Library: Foundation +// Package: DateTime +// Module: Clock +// +// Definition of the Clock class. +// +// Copyright (c) 2013, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Clock_INCLUDED +#define Foundation_Clock_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Clock + /// A Clock stores a monotonic* clock value + /// with (theoretical) microseconds resolution. + /// Clocks can be compared with each other + /// and simple arithmetics are supported. + /// + /// [*] Note that Clock values are only monotonic if + /// the operating system provides a monotonic clock. + /// The monotonic() function can be used to check whether + /// the system's clock is monotonic. + /// + /// Monotonic Clock is available on Windows, Linux, OS X + /// and on POSIX platforms supporting clock_gettime() with CLOCK_MONOTONIC. + /// + /// Clock values are relative to a system-dependent epoch time + /// (usually the system's startup time) and have no relation + /// to the time of day. +{ +public: + typedef Int64 ClockVal; + /// Monotonic clock value in microsecond resolution. + + typedef Int64 ClockDiff; + /// Difference between two ClockVal values in microseconds. + + static const ClockVal CLOCKVAL_MIN; /// Minimum clock value. + static const ClockVal CLOCKVAL_MAX; /// Maximum clock value. + + Clock(); + /// Creates a Clock with the current system clock value. + + Clock(ClockVal tv); + /// Creates a Clock from the given clock value. + + Clock(const Clock& other); + /// Copy constructor. + + ~Clock(); + /// Destroys the Clock. + + Clock& operator = (const Clock& other); + Clock& operator = (ClockVal tv); + + void swap(Clock& clock); + /// Swaps the Clock with another one. + + void update(); + /// Updates the Clock with the current system clock. + + bool operator == (const Clock& ts) const; + bool operator != (const Clock& ts) const; + bool operator > (const Clock& ts) const; + bool operator >= (const Clock& ts) const; + bool operator < (const Clock& ts) const; + bool operator <= (const Clock& ts) const; + + Clock operator + (ClockDiff d) const; + Clock operator - (ClockDiff d) const; + ClockDiff operator - (const Clock& ts) const; + Clock& operator += (ClockDiff d); + Clock& operator -= (ClockDiff d); + + ClockVal microseconds() const; + /// Returns the clock value expressed in microseconds + /// since the system-specific epoch time (usually system + /// startup). + + ClockVal raw() const; + /// Returns the clock value expressed in microseconds + /// since the system-specific epoch time (usually system + /// startup). + /// + /// Same as microseconds(). + + ClockDiff elapsed() const; + /// Returns the time elapsed since the time denoted by + /// the Clock instance. Equivalent to Clock() - *this. + + bool isElapsed(ClockDiff interval) const; + /// Returns true iff the given interval has passed + /// since the time denoted by the Clock instance. + + static ClockDiff resolution(); + /// Returns the resolution in units per second. + /// Since the Clock clas has microsecond resolution, + /// the returned value is always 1000000. + + static ClockDiff accuracy(); + /// Returns the system's clock accuracy in microseconds. + + static bool monotonic(); + /// Returns true iff the system's clock is monotonic. + +private: + ClockVal _clock; +}; + + +// +// inlines +// +inline bool Clock::operator == (const Clock& ts) const +{ + return _clock == ts._clock; +} + + +inline bool Clock::operator != (const Clock& ts) const +{ + return _clock != ts._clock; +} + + +inline bool Clock::operator > (const Clock& ts) const +{ + return _clock > ts._clock; +} + + +inline bool Clock::operator >= (const Clock& ts) const +{ + return _clock >= ts._clock; +} + + +inline bool Clock::operator < (const Clock& ts) const +{ + return _clock < ts._clock; +} + + +inline bool Clock::operator <= (const Clock& ts) const +{ + return _clock <= ts._clock; +} + + +inline Clock Clock::operator + (Clock::ClockDiff d) const +{ + return Clock(_clock + d); +} + + +inline Clock Clock::operator - (Clock::ClockDiff d) const +{ + return Clock(_clock - d); +} + + +inline Clock::ClockDiff Clock::operator - (const Clock& ts) const +{ + return _clock - ts._clock; +} + + +inline Clock& Clock::operator += (Clock::ClockDiff d) +{ + _clock += d; + return *this; +} + + +inline Clock& Clock::operator -= (Clock::ClockDiff d) +{ + _clock -= d; + return *this; +} + + +inline Clock::ClockVal Clock::microseconds() const +{ + return _clock; +} + + +inline Clock::ClockDiff Clock::elapsed() const +{ + Clock now; + return now - *this; +} + + +inline bool Clock::isElapsed(Clock::ClockDiff interval) const +{ + Clock now; + Clock::ClockDiff diff = now - *this; + return diff >= interval; +} + + +inline Clock::ClockDiff Clock::resolution() +{ + return 1000000; +} + + +inline void swap(Clock& s1, Clock& s2) +{ + s1.swap(s2); +} + + +inline Clock::ClockVal Clock::raw() const +{ + return _clock; +} + + +} // namespace Poco + + +#endif // Foundation_Clock_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Condition.h b/contrib/libs/poco/Foundation/include/Poco/Condition.h new file mode 100644 index 0000000000..3340533df1 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Condition.h @@ -0,0 +1,137 @@ +// +// Condition.h +// +// Library: Foundation +// Package: Threading +// Module: Condition +// +// Definition of the Condition class template. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Condition_INCLUDED +#define Foundation_Condition_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/ScopedUnlock.h" +#include "Poco/Event.h" +#include "Poco/Exception.h" +#include <deque> + + +namespace Poco { + + +class Foundation_API Condition + /// A Condition is a synchronization object used to block a thread + /// until a particular condition is met. + /// A Condition object is always used in conjunction with + /// a Mutex (or FastMutex) object. + /// + /// Condition objects are similar to POSIX condition variables, which the + /// difference that Condition is not subject to spurious wakeups. + /// + /// Threads waiting on a Condition are resumed in FIFO order. +{ +public: + Condition(); + /// Creates the Condition. + + ~Condition(); + /// Destroys the Condition. + + template <class Mtx> + void wait(Mtx& mutex) + /// Unlocks the mutex (which must be locked upon calling + /// wait()) and waits until the Condition is signalled. + /// + /// The given mutex will be locked again upon + /// leaving the function, even in case of an exception. + { + ScopedUnlock<Mtx> unlock(mutex, false); + Event event; + { + FastMutex::ScopedLock lock(_mutex); + mutex.unlock(); + enqueue(event); + } + event.wait(); + } + + template <class Mtx> + void wait(Mtx& mutex, long milliseconds) + /// Unlocks the mutex (which must be locked upon calling + /// wait()) and waits for the given time until the Condition is signalled. + /// + /// The given mutex will be locked again upon successfully leaving the + /// function, even in case of an exception. + /// + /// Throws a TimeoutException if the Condition is not signalled + /// within the given time interval. + { + if (!tryWait(mutex, milliseconds)) + throw TimeoutException(); + } + + template <class Mtx> + bool tryWait(Mtx& mutex, long milliseconds) + /// Unlocks the mutex (which must be locked upon calling + /// tryWait()) and waits for the given time until the Condition is signalled. + /// + /// The given mutex will be locked again upon leaving the + /// function, even in case of an exception. + /// + /// Returns true if the Condition has been signalled + /// within the given time interval, otherwise false. + { + ScopedUnlock<Mtx> unlock(mutex, false); + Event event; + { + FastMutex::ScopedLock lock(_mutex); + mutex.unlock(); + enqueue(event); + } + if (!event.tryWait(milliseconds)) + { + FastMutex::ScopedLock lock(_mutex); + dequeue(event); + return false; + } + return true; + } + + void signal(); + /// Signals the Condition and allows one waiting thread + /// to continue execution. + + void broadcast(); + /// Signals the Condition and allows all waiting + /// threads to continue their execution. + +protected: + void enqueue(Event& event); + void dequeue(); + void dequeue(Event& event); + +private: + Condition(const Condition&); + Condition& operator = (const Condition&); + + typedef std::deque<Event*> WaitQueue; + + FastMutex _mutex; + WaitQueue _waitQueue; +}; + + +} // namespace Poco + + +#endif // Foundation_Condition_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Config.h b/contrib/libs/poco/Foundation/include/Poco/Config.h new file mode 100644 index 0000000000..907db9c294 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Config.h @@ -0,0 +1,215 @@ +// +// Config.h +// +// Library: Foundation +// Package: Core +// Module: Foundation +// +// Feature configuration for the POCO libraries. +// +// Copyright (c) 2006-2016, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Config_INCLUDED +#define Foundation_Config_INCLUDED + + +#define POCO_CLICKHOUSE_PATCH 1 +#define POCO_ENABLE_CPP11 1 +#define POCO_ENABLE_SOO 1 +#define POCO_NO_AUTOMATIC_LIBS 1 +#define POCO_STATIC 1 +#define POCO_UNBUNDLED 1 + + +// Define to enable Windows Unicode (UTF-8) support +// NOTE: As of POCO C++ Libraries release 1.6.0, compiling POCO +// without POCO_WIN32_UTF8 defined on Windows is deprecated. +#define POCO_WIN32_UTF8 + + +// Define to enable C++11 support +// #define POCO_ENABLE_CPP11 + + +// Define to disable implicit linking +// #define POCO_NO_AUTOMATIC_LIBS + + +// Define to disable automatic initialization +// Defining this will disable ALL automatic +// initialization framework-wide (e.g. Net +// on Windows, all Data back-ends, etc). +// +// #define POCO_NO_AUTOMATIC_LIB_INIT + + +// Define to disable FPEnvironment support +// #define POCO_NO_FPENVIRONMENT + + +// Define if std::wstring is not available +// #define POCO_NO_WSTRING + + +// Define to disable shared memory +// #define POCO_NO_SHAREDMEMORY + + +// Define if no <locale> header is available (such as on WinCE) +// #define POCO_NO_LOCALE + + +// Define to desired default thread stack size +// Zero means OS default +#ifndef POCO_THREAD_STACK_SIZE + #define POCO_THREAD_STACK_SIZE 0 +#endif + + +// Define to override system-provided +// minimum thread priority value on POSIX +// platforms (returned by Poco::Thread::getMinOSPriority()). +// #define POCO_THREAD_PRIORITY_MIN 0 + + +// Define to override system-provided +// maximum thread priority value on POSIX +// platforms (returned by Poco::Thread::getMaxOSPriority()). +// #define POCO_THREAD_PRIORITY_MAX 31 + + +// Define to disable small object optimization. If not +// defined, Any and Dynamic::Var (and similar optimization +// candidates) will be auto-allocated on the stack in +// cases when value holder fits into POCO_SMALL_OBJECT_SIZE +// (see below). +// +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// !!! NOTE: Any/Dynamic::Var SOO will NOT work reliably !!! +// !!! without C++11 (std::aligned_storage in particular). !!! +// !!! Only comment this out if your compiler has support !!! +// !!! for std::aligned_storage. !!! +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// +#ifndef POCO_ENABLE_SOO +#define POCO_NO_SOO +#endif + + +// Small object size in bytes. When assigned to Any or Var, +// objects larger than this value will be alocated on the heap, +// while those smaller will be placement new-ed into an +// internal buffer. +#if !defined(POCO_SMALL_OBJECT_SIZE) && !defined(POCO_NO_SOO) + #define POCO_SMALL_OBJECT_SIZE 32 +#endif + + +// Define to disable compilation of DirectoryWatcher +// on platforms with no inotify. +// #define POCO_NO_INOTIFY + + +// Following are options to remove certain features +// to reduce library/executable size for smaller +// embedded platforms. By enabling these options, +// the size of a statically executable can be +// reduced by a few 100 Kbytes. + + +// No automatic registration of FileChannel in +// LoggingFactory - avoids FileChannel and friends +// being linked to executable. +// #define POCO_NO_FILECHANNEL + + +// No automatic registration of SplitterChannel in +// LoggingFactory - avoids SplitterChannel being +// linked to executable. +// #define POCO_NO_SPLITTERCHANNEL + + +// No automatic registration of SyslogChannel in +// LoggingFactory - avoids SyslogChannel being +// linked to executable on Unix/Linux systems. +// #define POCO_NO_SYSLOGCHANNEL + + +// Define to enable MSVC secure warnings +// #define POCO_MSVC_SECURE_WARNINGS + + +// No support for INI file configurations in +// Poco::Util::Application. +// #define POCO_UTIL_NO_INIFILECONFIGURATION + + +// No support for JSON configuration in +// Poco::Util::Application. Avoids linking of JSON +// library and saves a few 100 Kbytes. +// #define POCO_UTIL_NO_JSONCONFIGURATION + + +// No support for XML configuration in +// Poco::Util::Application. Avoids linking of XML +// library and saves a few 100 Kbytes. +// #define POCO_UTIL_NO_XMLCONFIGURATION + + +// No IPv6 support +// Define to disable IPv6 +// #define POCO_NET_NO_IPv6 + + +// Windows CE has no locale support +#if defined(_WIN32_WCE) + #define POCO_NO_LOCALE +#endif + + +// Enable the poco_debug_* and poco_trace_* macros +// even if the _DEBUG variable is not set. +// This allows the use of these macros in a release version. +// #define POCO_LOG_DEBUG + + +// OpenSSL on Windows +// +// Poco has its own OpenSSL build system. +// See <https://github.com/pocoproject/openssl/blob/master/README.md> +// for details. +// +// These options are Windows only. +// +// To disable the use of Poco-provided OpenSSL binaries, +// define POCO_EXTERNAL_OPENSSL. +// +// Possible values: +// POCO_EXTERNAL_OPENSSL_SLPRO: +// Automatically link OpenSSL libraries from OpenSSL Windows installer provided +// by Shining Light Productions <http://slproweb.com/products/Win32OpenSSL.html> +// The (global) library search path must be set accordingly. +// POCO_EXTERNAL_OPENSSL_DEFAULT: +// Automatically link OpenSSL libraries from standard OpenSSL Windows build. +// The (global) library search path must be set accordingly. +// empty or other value: +// Do not link any OpenSSL libraries automatically. You will have to edit the +// Visual C++ project files for Crypto and NetSSL_OpenSSL. +// #define POCO_EXTERNAL_OPENSSL POCO_EXTERNAL_OPENSSL_SLPRO + + +// Define to prevent changing the suffix for shared libraries +// to "d.so", "d.dll", etc. for _DEBUG builds in Poco::SharedLibrary. +// #define POCO_NO_SHARED_LIBRARY_DEBUG_SUFFIX + + +// Disarm POCO_DEPRECATED macro. +// #define POCO_NO_DEPRECATED + + +#endif // Foundation_Config_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Configurable.h b/contrib/libs/poco/Foundation/include/Poco/Configurable.h new file mode 100644 index 0000000000..cb260d3829 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Configurable.h @@ -0,0 +1,70 @@ +// +// Configurable.h +// +// Library: Foundation +// Package: Logging +// Module: Configurable +// +// Definition of the Configurable class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Configurable_INCLUDED +#define Foundation_Configurable_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Configurable + /// A simple interface that defines + /// getProperty() and setProperty() methods. + /// + /// This interface is implemented by Formatter and + /// Channel and is used to configure arbitrary + /// channels and formatters. + /// + /// A property is basically a name-value pair. For + /// simplicity, both names and values are strings. + /// Every property controls a certain aspect of a + /// Formatter or Channel. For example, the PatternFormatter's + /// formatting pattern is set via a property. + /// + /// NOTE: The following property names are use internally + /// by the logging framework and must not be used by + /// channels or formatters: + /// - class + /// - pattern (Channel) + /// - formatter (Channel) +{ +public: + Configurable(); + /// Creates the Configurable. + + virtual ~Configurable(); + /// Destroys the Configurable. + + virtual void setProperty(const std::string& name, const std::string& value) = 0; + /// Sets the property with the given name to the given value. + /// If a property with the given name is not supported, a + /// PropertyNotSupportedException is thrown. + + virtual std::string getProperty(const std::string& name) const = 0; + /// Returns the value of the property with the given name. + /// If a property with the given name is not supported, a + /// PropertyNotSupportedException is thrown. +}; + + +} // namespace Poco + + +#endif // Foundation_Configurable_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ConsoleChannel.h b/contrib/libs/poco/Foundation/include/Poco/ConsoleChannel.h new file mode 100644 index 0000000000..28aab6e3ef --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ConsoleChannel.h @@ -0,0 +1,187 @@ +// +// ConsoleChannel.h +// +// Library: Foundation +// Package: Logging +// Module: ConsoleChannel +// +// Definition of the ConsoleChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ConsoleChannel_INCLUDED +#define Foundation_ConsoleChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Mutex.h" +#include <ostream> + + +namespace Poco { + + +class Foundation_API ConsoleChannel: public Channel + /// A channel that writes to an ostream. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is contained + /// in the text. + /// + /// Similar to StreamChannel, except that a static + /// mutex is used to protect against multiple + /// console channels concurrently writing to the + /// same stream. +{ +public: + ConsoleChannel(); + /// Creates the channel and attaches std::clog. + + ConsoleChannel(std::ostream& str); + /// Creates the channel using the given stream. + + void log(const Message& msg); + /// Logs the given message to the channel's stream. + +protected: + ~ConsoleChannel(); + +private: + std::ostream& _str; + static FastMutex _mutex; +}; + + +class Foundation_API ColorConsoleChannel: public Channel + /// A channel that writes to an ostream. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Messages can be colored depending on priority. + /// The console device must support ANSI escape codes + /// in order to display colored messages. + /// + /// To enable message coloring, set the "enableColors" + /// property to true (default). Furthermore, colors can be + /// configured by setting the following properties + /// (default values are given in parenthesis): + /// + /// * traceColor (gray) + /// * debugColor (gray) + /// * informationColor (default) + /// * noticeColor (default) + /// * warningColor (yellow) + /// * errorColor (lightRed) + /// * criticalColor (lightRed) + /// * fatalColor (lightRed) + /// + /// The following color values are supported: + /// + /// * default + /// * black + /// * red + /// * green + /// * brown + /// * blue + /// * magenta + /// * cyan + /// * gray + /// * darkgray + /// * lightRed + /// * lightGreen + /// * yellow + /// * lightBlue + /// * lightMagenta + /// * lightCyan + /// * white + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is contained + /// in the text. + /// + /// Similar to StreamChannel, except that a static + /// mutex is used to protect against multiple + /// console channels concurrently writing to the + /// same stream. +{ +public: + ColorConsoleChannel(); + /// Creates the channel and attaches std::clog. + + ColorConsoleChannel(std::ostream& str); + /// Creates the channel using the given stream. + + void log(const Message& msg); + /// Logs the given message to the channel's stream. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name. + /// + /// The following properties are supported: + /// * enableColors: Enable or disable colors. + /// * traceColor: Specify color for trace messages. + /// * debugColor: Specify color for debug messages. + /// * informationColor: Specify color for information messages. + /// * noticeColor: Specify color for notice messages. + /// * warningColor: Specify color for warning messages. + /// * errorColor: Specify color for error messages. + /// * criticalColor: Specify color for critical messages. + /// * fatalColor: Specify color for fatal messages. + /// + /// See the class documentation for a list of supported color values. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + /// See setProperty() for a description of the supported + /// properties. + +protected: + enum Color + { + CC_DEFAULT = 0x0027, + CC_BLACK = 0x001e, + CC_RED = 0x001f, + CC_GREEN = 0x0020, + CC_BROWN = 0x0021, + CC_BLUE = 0x0022, + CC_MAGENTA = 0x0023, + CC_CYAN = 0x0024, + CC_GRAY = 0x0025, + CC_DARKGRAY = 0x011e, + CC_LIGHTRED = 0x011f, + CC_LIGHTGREEN = 0x0120, + CC_YELLOW = 0x0121, + CC_LIGHTBLUE = 0x0122, + CC_LIGHTMAGENTA = 0x0123, + CC_LIGHTCYAN = 0x0124, + CC_WHITE = 0x0125 + }; + + ~ColorConsoleChannel(); + Color parseColor(const std::string& color) const; + std::string formatColor(Color color) const; + void initColors(); + +private: + std::ostream& _str; + bool _enableColors; + Color _colors[9]; + static FastMutex _mutex; + static const std::string CSI; +}; + + +} // namespace Poco + + +#endif // Foundation_ConsoleChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/CountingStream.h b/contrib/libs/poco/Foundation/include/Poco/CountingStream.h new file mode 100644 index 0000000000..17da1e4e71 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/CountingStream.h @@ -0,0 +1,237 @@ +// +// CountingStream.h +// +// Library: Foundation +// Package: Streams +// Module: CountingStream +// +// Definition of the CountingStreamBuf, CountingInputStream and CountingOutputStream classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_CountingStream_INCLUDED +#define Foundation_CountingStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API CountingStreamBuf: public UnbufferedStreamBuf + /// This stream buffer counts all characters and lines + /// going through it. +{ +public: + CountingStreamBuf(); + /// Creates an unconnected CountingStreamBuf. + + CountingStreamBuf(std::istream& istr); + /// Creates the CountingStreamBuf and connects it + /// to the given input stream. + + CountingStreamBuf(std::ostream& ostr); + /// Creates the CountingStreamBuf and connects it + /// to the given output stream. + + ~CountingStreamBuf(); + /// Destroys the CountingStream. + + int chars() const; + /// Returns the total number of characters. + + int lines() const; + /// Returns the total number of lines. + + int pos() const; + /// Returns the number of characters on the current line. + + void reset(); + /// Resets all counters. + + void setCurrentLineNumber(int line); + /// Sets the current line number. + /// + /// This is mainly useful when parsing C/C++ + /// preprocessed source code containing #line directives. + + int getCurrentLineNumber() const; + /// Returns the current line number (same as lines()). + + void addChars(int chars); + /// Add to the total number of characters. + + void addLines(int lines); + /// Add to the total number of lines. + + void addPos(int pos); + /// Add to the number of characters on the current line. + +protected: + int readFromDevice(); + int writeToDevice(char c); + +private: + std::istream* _pIstr; + std::ostream* _pOstr; + int _chars; + int _lines; + int _pos; +}; + + +class Foundation_API CountingIOS: public virtual std::ios + /// The base class for CountingInputStream and CountingOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + CountingIOS(); + /// Creates the basic stream and leaves it unconnected. + + CountingIOS(std::istream& istr); + /// Creates the basic stream and connects it + /// to the given input stream. + + CountingIOS(std::ostream& ostr); + /// Creates the basic stream and connects it + /// to the given output stream. + + ~CountingIOS(); + /// Destroys the stream. + + int chars() const; + /// Returns the total number of characters. + + int lines() const; + /// Returns the total number of lines. + + int pos() const; + /// Returns the number of characters on the current line. + + void reset(); + /// Resets all counters. + + void setCurrentLineNumber(int line); + /// Sets the current line number. + /// + /// This is mainly useful when parsing C/C++ + /// preprocessed source code containing #line directives. + + int getCurrentLineNumber() const; + /// Returns the current line number (same as lines()). + + void addChars(int chars); + /// Add to the total number of characters. + + void addLines(int lines); + /// Add to the total number of lines. + + void addPos(int pos); + /// Add to the number of characters on the current line. + + CountingStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + CountingStreamBuf _buf; +}; + + +class Foundation_API CountingInputStream: public CountingIOS, public std::istream + /// This stream counts all characters and lines + /// going through it. This is useful for lexers and parsers + /// that need to determine the current position in the stream. +{ +public: + CountingInputStream(std::istream& istr); + /// Creates the CountingInputStream and connects it + /// to the given input stream. + + ~CountingInputStream(); + /// Destroys the stream. +}; + + +class Foundation_API CountingOutputStream: public CountingIOS, public std::ostream + /// This stream counts all characters and lines + /// going through it. +{ +public: + CountingOutputStream(); + /// Creates an unconnected CountingOutputStream. + + CountingOutputStream(std::ostream& ostr); + /// Creates the CountingOutputStream and connects it + /// to the given output stream. + + ~CountingOutputStream(); + /// Destroys the CountingOutputStream. +}; + + +// +// inlines +// +inline int CountingStreamBuf::chars() const +{ + return _chars; +} + + +inline int CountingStreamBuf::lines() const +{ + return _lines; +} + + +inline int CountingStreamBuf::pos() const +{ + return _pos; +} + + +inline int CountingStreamBuf::getCurrentLineNumber() const +{ + return _lines; +} + + +inline int CountingIOS::chars() const +{ + return _buf.chars(); +} + + +inline int CountingIOS::lines() const +{ + return _buf.lines(); +} + + +inline int CountingIOS::pos() const +{ + return _buf.pos(); +} + + +inline int CountingIOS::getCurrentLineNumber() const +{ + return _buf.getCurrentLineNumber(); +} + + +} // namespace Poco + + +#endif // Foundation_CountingStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DateTime.h b/contrib/libs/poco/Foundation/include/Poco/DateTime.h new file mode 100644 index 0000000000..ab69894719 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DateTime.h @@ -0,0 +1,415 @@ +// +// DateTime.h +// +// Library: Foundation +// Package: DateTime +// Module: DateTime +// +// Definition of the DateTime class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DateTime_INCLUDED +#define Foundation_DateTime_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" + + +namespace Poco { + + +class Foundation_API DateTime + /// This class represents an instant in time, expressed + /// in years, months, days, hours, minutes, seconds + /// and milliseconds based on the Gregorian calendar. + /// The class is mainly useful for conversions between + /// UTC, Julian day and Gregorian calendar dates. + /// + /// The date and time stored in a DateTime is always in UTC + /// (Coordinated Universal Time) and thus independent of the + /// timezone in effect on the system. + /// + /// Conversion calculations are based on algorithms + /// collected and described by Peter Baum at + /// http://vsg.cape.com/~pbaum/date/date0.htm + /// + /// Internally, this class stores a date/time in two + /// forms (UTC and broken down) for performance reasons. Only use + /// this class for conversions between date/time representations. + /// Use the Timestamp class for everything else. + /// + /// Notes: + /// * Zero is a valid year (in accordance with ISO 8601 and astronomical year numbering) + /// * Year zero (0) is a leap year + /// * Negative years (years preceding 1 BC) are not supported + /// + /// For more information, please see: + /// * http://en.wikipedia.org/wiki/Gregorian_Calendar + /// * http://en.wikipedia.org/wiki/Julian_day + /// * http://en.wikipedia.org/wiki/UTC + /// * http://en.wikipedia.org/wiki/ISO_8601 +{ +public: + enum Months + /// Symbolic names for month numbers (1 to 12). + { + JANUARY = 1, + FEBRUARY, + MARCH, + APRIL, + MAY, + JUNE, + JULY, + AUGUST, + SEPTEMBER, + OCTOBER, + NOVEMBER, + DECEMBER + }; + + enum DaysOfWeek + /// Symbolic names for week day numbers (0 to 6). + { + SUNDAY = 0, + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + FRIDAY, + SATURDAY + }; + + DateTime(); + /// Creates a DateTime for the current date and time. + + DateTime(const Timestamp& timestamp); + /// Creates a DateTime for the date and time given in + /// a Timestamp. + + DateTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); + /// Creates a DateTime for the given Gregorian date and time. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 60 (allowing leap seconds). + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + DateTime(double julianDay); + /// Creates a DateTime for the given Julian day. + + DateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff); + /// Creates a DateTime from an UtcTimeVal and a TimeDiff. + /// + /// Mainly used internally by DateTime and friends. + + DateTime(const DateTime& dateTime); + /// Copy constructor. Creates the DateTime from another one. + + ~DateTime(); + /// Destroys the DateTime. + + DateTime& operator = (const DateTime& dateTime); + /// Assigns another DateTime. + + DateTime& operator = (const Timestamp& timestamp); + /// Assigns a Timestamp. + + DateTime& operator = (double julianDay); + /// Assigns a Julian day. + + DateTime& assign(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microseconds = 0); + /// Assigns a Gregorian date and time. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 60 (allowing leap seconds). + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + void swap(DateTime& dateTime); + /// Swaps the DateTime with another one. + + int year() const; + /// Returns the year. + + int month() const; + /// Returns the month (1 to 12). + + int week(int firstDayOfWeek = MONDAY) const; + /// Returns the week number within the year. + /// FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). + /// The returned week number will be from 0 to 53. Week number 1 is the week + /// containing January 4. This is in accordance to ISO 8601. + /// + /// The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started + /// on a Saturday, week 1 will be the week starting on Monday, January 3. + /// January 1 and 2 will fall within week 0 (or the last week of the previous year). + /// + /// For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1. + /// There will be no week 0 in 2007. + + int day() const; + /// Returns the day witin the month (1 to 31). + + int dayOfWeek() const; + /// Returns the weekday (0 to 6, where + /// 0 = Sunday, 1 = Monday, ..., 6 = Saturday). + + int dayOfYear() const; + /// Returns the number of the day in the year. + /// January 1 is 1, February 1 is 32, etc. + + int hour() const; + /// Returns the hour (0 to 23). + + int hourAMPM() const; + /// Returns the hour (0 to 12). + + bool isAM() const; + /// Returns true if hour < 12; + + bool isPM() const; + /// Returns true if hour >= 12. + + int minute() const; + /// Returns the minute (0 to 59). + + int second() const; + /// Returns the second (0 to 59). + + int millisecond() const; + /// Returns the millisecond (0 to 999) + + int microsecond() const; + /// Returns the microsecond (0 to 999) + + double julianDay() const; + /// Returns the julian day for the date and time. + + Timestamp timestamp() const; + /// Returns the date and time expressed as a Timestamp. + + Timestamp::UtcTimeVal utcTime() const; + /// Returns the date and time expressed in UTC-based + /// time. UTC base time is midnight, October 15, 1582. + /// Resolution is 100 nanoseconds. + + bool operator == (const DateTime& dateTime) const; + bool operator != (const DateTime& dateTime) const; + bool operator < (const DateTime& dateTime) const; + bool operator <= (const DateTime& dateTime) const; + bool operator > (const DateTime& dateTime) const; + bool operator >= (const DateTime& dateTime) const; + + DateTime operator + (const Timespan& span) const; + DateTime operator - (const Timespan& span) const; + Timespan operator - (const DateTime& dateTime) const; + DateTime& operator += (const Timespan& span); + DateTime& operator -= (const Timespan& span); + + void makeUTC(int tzd); + /// Converts a local time into UTC, by applying the given time zone differential. + + void makeLocal(int tzd); + /// Converts a UTC time into a local time, by applying the given time zone differential. + + static bool isLeapYear(int year); + /// Returns true if the given year is a leap year; + /// false otherwise. + + static int daysOfMonth(int year, int month); + /// Returns the number of days in the given month + /// and year. Month is from 1 to 12. + + static bool isValid(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); + /// Checks if the given date and time is valid + /// (all arguments are within a proper range). + /// + /// Returns true if all arguments are valid, false otherwise. + +protected: + static double toJulianDay(Timestamp::UtcTimeVal utcTime); + /// Computes the Julian day for an UTC time. + + static double toJulianDay(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); + /// Computes the Julian day for a gregorian calendar date and time. + /// See <http://vsg.cape.com/~pbaum/date/jdimp.htm>, section 2.3.1 for the algorithm. + + static Timestamp::UtcTimeVal toUtcTime(double julianDay); + /// Computes the UTC time for a Julian day. + + void computeGregorian(double julianDay); + /// Computes the Gregorian date for the given Julian day. + /// See <http://vsg.cape.com/~pbaum/date/injdimp.htm>, section 3.3.1 for the algorithm. + + void computeDaytime(); + /// Extracts the daytime (hours, minutes, seconds, etc.) from the stored utcTime. + +private: + void checkLimit(short& lower, short& higher, short limit); + void normalize(); + ///utility functions used to correct the overflow in computeGregorian + + Timestamp::UtcTimeVal _utcTime; + short _year; + short _month; + short _day; + short _hour; + short _minute; + short _second; + short _millisecond; + short _microsecond; +}; + + +// +// inlines +// +inline Timestamp DateTime::timestamp() const +{ + return Timestamp::fromUtcTime(_utcTime); +} + + +inline Timestamp::UtcTimeVal DateTime::utcTime() const +{ + return _utcTime; +} + + +inline int DateTime::year() const +{ + return _year; +} + + +inline int DateTime::month() const +{ + return _month; +} + + +inline int DateTime::day() const +{ + return _day; +} + + +inline int DateTime::hour() const +{ + return _hour; +} + + +inline int DateTime::hourAMPM() const +{ + if (_hour < 1) + return 12; + else if (_hour > 12) + return _hour - 12; + else + return _hour; +} + + +inline bool DateTime::isAM() const +{ + return _hour < 12; +} + + +inline bool DateTime::isPM() const +{ + return _hour >= 12; +} + + +inline int DateTime::minute() const +{ + return _minute; +} + + +inline int DateTime::second() const +{ + return _second; +} + + +inline int DateTime::millisecond() const +{ + return _millisecond; +} + + +inline int DateTime::microsecond() const +{ + return _microsecond; +} + + +inline bool DateTime::operator == (const DateTime& dateTime) const +{ + return _utcTime == dateTime._utcTime; +} + + +inline bool DateTime::operator != (const DateTime& dateTime) const +{ + return _utcTime != dateTime._utcTime; +} + + +inline bool DateTime::operator < (const DateTime& dateTime) const +{ + return _utcTime < dateTime._utcTime; +} + + +inline bool DateTime::operator <= (const DateTime& dateTime) const +{ + return _utcTime <= dateTime._utcTime; +} + + +inline bool DateTime::operator > (const DateTime& dateTime) const +{ + return _utcTime > dateTime._utcTime; +} + + +inline bool DateTime::operator >= (const DateTime& dateTime) const +{ + return _utcTime >= dateTime._utcTime; +} + + +inline bool DateTime::isLeapYear(int year) +{ + return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0); +} + + +inline void swap(DateTime& d1, DateTime& d2) +{ + d1.swap(d2); +} + + +} // namespace Poco + + +#endif // Foundation_DateTime_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DateTimeFormat.h b/contrib/libs/poco/Foundation/include/Poco/DateTimeFormat.h new file mode 100644 index 0000000000..8f222d091f --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DateTimeFormat.h @@ -0,0 +1,109 @@ +// +// DateTimeFormat.h +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeFormat +// +// Definition of the DateTimeFormat class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DateTimeFormat_INCLUDED +#define Foundation_DateTimeFormat_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API DateTimeFormat + /// Definition of date/time formats and various + /// constants used by DateTimeFormatter and DateTimeParser. +{ +public: + // predefined date formats + static const std::string ISO8601_FORMAT; + /// The date/time format defined in the ISO 8601 standard. + /// + /// Examples: + /// 2005-01-01T12:00:00+01:00 + /// 2005-01-01T11:00:00Z + + static const std::string ISO8601_FRAC_FORMAT; + /// The date/time format defined in the ISO 8601 standard, + /// with fractional seconds. + /// + /// Examples: + /// 2005-01-01T12:00:00.000000+01:00 + /// 2005-01-01T11:00:00.000000Z + + static const std::string RFC822_FORMAT; + /// The date/time format defined in RFC 822 (obsoleted by RFC 1123). + /// + /// Examples: + /// Sat, 1 Jan 05 12:00:00 +0100 + /// Sat, 1 Jan 05 11:00:00 GMT + + static const std::string RFC1123_FORMAT; + /// The date/time format defined in RFC 1123 (obsoletes RFC 822). + /// + /// Examples: + /// Sat, 1 Jan 2005 12:00:00 +0100 + /// Sat, 1 Jan 2005 11:00:00 GMT + + static const std::string HTTP_FORMAT; + /// The date/time format defined in the HTTP specification (RFC 2616), + /// which is basically a variant of RFC 1036 with a zero-padded day field. + /// + /// Examples: + /// Sat, 01 Jan 2005 12:00:00 +0100 + /// Sat, 01 Jan 2005 11:00:00 GMT + + static const std::string RFC850_FORMAT; + /// The date/time format defined in RFC 850 (obsoleted by RFC 1036). + /// + /// Examples: + /// Saturday, 1-Jan-05 12:00:00 +0100 + /// Saturday, 1-Jan-05 11:00:00 GMT + + static const std::string RFC1036_FORMAT; + /// The date/time format defined in RFC 1036 (obsoletes RFC 850). + /// + /// Examples: + /// Saturday, 1 Jan 05 12:00:00 +0100 + /// Saturday, 1 Jan 05 11:00:00 GMT + + static const std::string ASCTIME_FORMAT; + /// The date/time format produced by the ANSI C asctime() function. + /// + /// Example: + /// Sat Jan 1 12:00:00 2005 + + static const std::string SORTABLE_FORMAT; + /// A simple, sortable date/time format. + /// + /// Example: + /// 2005-01-01 12:00:00 + + + // names used by formatter and parser + static const std::string WEEKDAY_NAMES[7]; + /// English names of week days (Sunday, Monday, Tuesday, ...). + + static const std::string MONTH_NAMES[12]; + /// English names of months (January, February, ...). +}; + + +} // namespace Poco + + +#endif // Foundation_DateTimeFormat_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DateTimeFormatter.h b/contrib/libs/poco/Foundation/include/Poco/DateTimeFormatter.h new file mode 100644 index 0000000000..3d6e5ed805 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DateTimeFormatter.h @@ -0,0 +1,215 @@ +// +// DateTimeFormatter.h +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeFormatter +// +// Definition of the DateTimeFormatter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DateTimeFormatter_INCLUDED +#define Foundation_DateTimeFormatter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DateTime.h" +#include "Poco/LocalDateTime.h" + + +namespace Poco { + + +class Timestamp; +class Timespan; + + +class Foundation_API DateTimeFormatter + /// This class converts dates and times into strings, supporting a + /// variety of standard and custom formats. + /// + /// There are two kind of static member functions: + /// * format* functions return a std::string containing + /// the formatted value. + /// * append* functions append the formatted value to + /// an existing string. +{ +public: + enum + { + UTC = 0xFFFF /// Special value for timeZoneDifferential denoting UTC. + }; + + static std::string format(const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential = UTC); + /// Formats the given timestamp according to the given format. + /// The format string is used as a template to format the date and + /// is copied character by character except for the following special characters, + /// which are replaced by the corresponding value. + /// + /// * %w - abbreviated weekday (Mon, Tue, ...) + /// * %W - full weekday (Monday, Tuesday, ...) + /// * %b - abbreviated month (Jan, Feb, ...) + /// * %B - full month (January, February, ...) + /// * %d - zero-padded day of month (01 .. 31) + /// * %e - day of month (1 .. 31) + /// * %f - space-padded day of month ( 1 .. 31) + /// * %m - zero-padded month (01 .. 12) + /// * %n - month (1 .. 12) + /// * %o - space-padded month ( 1 .. 12) + /// * %y - year without century (70) + /// * %Y - year with century (1970) + /// * %H - hour (00 .. 23) + /// * %h - hour (00 .. 12) + /// * %a - am/pm + /// * %A - AM/PM + /// * %M - minute (00 .. 59) + /// * %S - second (00 .. 59) + /// * %s - seconds and microseconds (equivalent to %S.%F) + /// * %i - millisecond (000 .. 999) + /// * %c - centisecond (0 .. 9) + /// * %F - fractional seconds/microseconds (000000 - 999999) + /// * %z - time zone differential in ISO 8601 format (Z or +NN.NN) + /// * %Z - time zone differential in RFC format (GMT or +NNNN) + /// * %% - percent sign + /// + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static std::string format(const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential = UTC); + /// Formats the given date and time according to the given format. + /// See format(const Timestamp&, const std::string&, int) for more information. + + static std::string format(const LocalDateTime& dateTime, const std::string& fmt); + /// Formats the given local date and time according to the given format. + /// See format(const Timestamp&, const std::string&, int) for more information. + + static std::string format(const Timespan& timespan, const std::string& fmt = "%dd %H:%M:%S.%i"); + /// Formats the given timespan according to the given format. + /// The format string is used as a template to format the date and + /// is copied character by character except for the following special characters, + /// which are replaced by the corresponding value. + /// + /// * %d - days + /// * %H - hours (00 .. 23) + /// * %h - total hours (0 .. n) + /// * %M - minutes (00 .. 59) + /// * %m - total minutes (0 .. n) + /// * %S - seconds (00 .. 59) + /// * %s - total seconds (0 .. n) + /// * %i - milliseconds (000 .. 999) + /// * %c - centisecond (0 .. 9) + /// * %F - fractional seconds/microseconds (000000 - 999999) + /// * %% - percent sign + + static void append(std::string& str, const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential = UTC); + /// Formats the given timestamp according to the given format and appends it to str. + /// + /// See format() for documentation of the formatting string. + + static void append(std::string& str, const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential = UTC); + /// Formats the given date and time according to the given format and appends it to str. + /// + /// See format() for documentation of the formatting string. + + static void append(std::string& str, const LocalDateTime& dateTime, const std::string& fmt); + /// Formats the given local date and time according to the given format and appends it to str. + /// + /// See format() for documentation of the formatting string. + + static void append(std::string& str, const Timespan& timespan, const std::string& fmt = "%dd %H:%M:%S.%i"); + /// Formats the given timespan according to the given format and appends it to str. + /// + /// See format() for documentation of the formatting string. + + static std::string tzdISO(int timeZoneDifferential); + /// Formats the given timezone differential in ISO format. + /// If timeZoneDifferential is UTC, "Z" is returned, + /// otherwise, +HH.MM (or -HH.MM) is returned. + + static std::string tzdRFC(int timeZoneDifferential); + /// Formats the given timezone differential in RFC format. + /// If timeZoneDifferential is UTC, "GMT" is returned, + /// otherwise ++HHMM (or -HHMM) is returned. + + static void tzdISO(std::string& str, int timeZoneDifferential); + /// Formats the given timezone differential in ISO format + /// and appends it to the given string. + /// If timeZoneDifferential is UTC, "Z" is returned, + /// otherwise, +HH.MM (or -HH.MM) is returned. + + static void tzdRFC(std::string& str, int timeZoneDifferential); + /// Formats the given timezone differential in RFC format + /// and appends it to the given string. + /// If timeZoneDifferential is UTC, "GMT" is returned, + /// otherwise ++HHMM (or -HHMM) is returned. +}; + + +// +// inlines +// +inline std::string DateTimeFormatter::format(const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential) +{ + DateTime dateTime(timestamp); + return format(dateTime, fmt, timeZoneDifferential); +} + + +inline std::string DateTimeFormatter::format(const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential) +{ + std::string result; + result.reserve(64); + append(result, dateTime, fmt, timeZoneDifferential); + return result; +} + + +inline std::string DateTimeFormatter::format(const LocalDateTime& dateTime, const std::string& fmt) +{ + return format(dateTime._dateTime, fmt, dateTime._tzd); +} + + +inline std::string DateTimeFormatter::format(const Timespan& timespan, const std::string& fmt) +{ + std::string result; + result.reserve(32); + append(result, timespan, fmt); + return result; +} + + +inline void DateTimeFormatter::append(std::string& str, const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential) +{ + DateTime dateTime(timestamp); + append(str, dateTime, fmt, timeZoneDifferential); +} + + +inline std::string DateTimeFormatter::tzdISO(int timeZoneDifferential) +{ + std::string result; + result.reserve(8); + tzdISO(result, timeZoneDifferential); + return result; +} + + +inline std::string DateTimeFormatter::tzdRFC(int timeZoneDifferential) +{ + std::string result; + result.reserve(8); + tzdRFC(result, timeZoneDifferential); + return result; +} + + +} // namespace Poco + + +#endif // Foundation_DateTimeFormatter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DateTimeParser.h b/contrib/libs/poco/Foundation/include/Poco/DateTimeParser.h new file mode 100644 index 0000000000..28ebbe7562 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DateTimeParser.h @@ -0,0 +1,116 @@ +// +// DateTimeParser.h +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeParser +// +// Definition of the DateTimeParser class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DateTimeParser_INCLUDED +#define Foundation_DateTimeParser_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DateTime.h" + + +namespace Poco { + + +class Foundation_API DateTimeParser + /// This class provides a method for parsing dates and times + /// from strings. All parsing methods do their best to + /// parse a meaningful result, even from malformed input + /// strings. + /// + /// The returned DateTime will always contain a time in the same + /// timezone as the time in the string. Call DateTime::makeUTC() + /// with the timeZoneDifferential returned by parse() to convert + /// the DateTime to UTC. + /// + /// Note: When parsing a time in 12-hour (AM/PM) format, the hour + /// (%h) must be parsed before the AM/PM designator (%a, %A), + /// otherwise the AM/PM designator will be ignored. + /// + /// See the DateTimeFormatter class for a list of supported format specifiers. + /// In addition to the format specifiers supported by DateTimeFormatter, an + /// additional specifier is supported: %r will parse a year given by either + /// two or four digits. Years 69-00 are interpreted in the 20th century + /// (1969-2000), years 01-68 in the 21th century (2001-2068). + /// + /// Note that in the current implementation all characters other than format specifiers in + /// the format string are ignored/not matched against the date/time string. This may + /// lead to non-error results even with nonsense input strings. + /// This may change in a future version to a more strict behavior. + /// If more strict format validation of date/time strings is required, a regular + /// expression could be used for initial validation, before passing the string + /// to DateTimeParser. +{ +public: + static void parse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential); + /// Parses a date and time in the given format from the given string. + /// Throws a SyntaxException if the string cannot be successfully parsed. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static DateTime parse(const std::string& fmt, const std::string& str, int& timeZoneDifferential); + /// Parses a date and time in the given format from the given string. + /// Throws a SyntaxException if the string cannot be successfully parsed. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static bool tryParse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential); + /// Parses a date and time in the given format from the given string. + /// Returns true if the string has been successfully parsed, false otherwise. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static void parse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential); + /// Parses a date and time from the given dateTime string. Before parsing, the method + /// examines the dateTime string for a known date/time format. + /// Throws a SyntaxException if the string cannot be successfully parsed. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static DateTime parse(const std::string& str, int& timeZoneDifferential); + /// Parses a date and time from the given dateTime string. Before parsing, the method + /// examines the dateTime string for a known date/time format. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static bool tryParse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential); + /// Parses a date and time from the given dateTime string. Before parsing, the method + /// examines the dateTime string for a known date/time format. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static int parseMonth(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Tries to interpret the given range as a month name. The range must be at least + /// three characters long. + /// Returns the month number (1 .. 12) if the month name is valid. Otherwise throws + /// a SyntaxException. + + static int parseDayOfWeek(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Tries to interpret the given range as a weekday name. The range must be at least + /// three characters long. + /// Returns the weekday number (0 .. 6, where 0 = Synday, 1 = Monday, etc.) if the + /// weekday name is valid. Otherwise throws a SyntaxException. + +protected: + static int parseTZD(std::string::const_iterator& it, const std::string::const_iterator& end); + static int parseAMPM(std::string::const_iterator& it, const std::string::const_iterator& end, int hour); +}; + + +} // namespace Poco + + +#endif // Foundation_DateTimeParser_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Debugger.h b/contrib/libs/poco/Foundation/include/Poco/Debugger.h new file mode 100644 index 0000000000..f1de9fc38b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Debugger.h @@ -0,0 +1,70 @@ +// +// Debugger.h +// +// Library: Foundation +// Package: Core +// Module: Debugger +// +// Definition of the Debugger class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Debugger_INCLUDED +#define Foundation_Debugger_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Debugger + /// The Debugger class provides an interface to the debugger. + /// The presence of a debugger can be checked for, + /// messages can be written to the debugger's log window + /// and a break into the debugger can be enforced. + /// The methods only work if the program is compiled + /// in debug mode (the macro _DEBUG is defined). +{ +public: + static bool isAvailable(); + /// Returns true if a debugger is available, false otherwise. + /// On Windows, this function uses the IsDebuggerPresent() + /// function. + /// On Unix, this function returns true if the environment + /// variable POCO_ENABLE_DEBUGGER is set. + + static void message(const std::string& msg); + /// Writes a message to the debugger log, if available, otherwise to + /// standard error output. + + static void message(const std::string& msg, const char* file, int line); + /// Writes a message to the debugger log, if available, otherwise to + /// standard error output. + + static void enter(); + /// Breaks into the debugger, if it is available. + /// On Windows, this is done using the DebugBreak() function. + /// On Unix, the SIGINT signal is raised. + + static void enter(const std::string& msg); + /// Writes a debug message to the debugger log and breaks into it. + + static void enter(const std::string& msg, const char* file, int line); + /// Writes a debug message to the debugger log and breaks into it. + + static void enter(const char* file, int line); + /// Writes a debug message to the debugger log and breaks into it. +}; + + +} // namespace Poco + + +#endif // Foundation_Debugger_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DefaultStrategy.h b/contrib/libs/poco/Foundation/include/Poco/DefaultStrategy.h new file mode 100644 index 0000000000..6a095114eb --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DefaultStrategy.h @@ -0,0 +1,226 @@ +// +// DefaultStrategy.h +// +// Library: Foundation +// Package: Events +// Module: DefaultStrategy +// +// Implementation of the DefaultStrategy template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DefaultStrategy_INCLUDED +#define Foundation_DefaultStrategy_INCLUDED + + +#include "Poco/NotificationStrategy.h" +#include "Poco/SharedPtr.h" +#include <vector> + + +namespace Poco { + + +template <class TArgs, class TDelegate> +class DefaultStrategy: public NotificationStrategy<TArgs, TDelegate> + /// Default notification strategy. + /// + /// Internally, a std::vector<> is used to store + /// delegate objects. Delegates are invoked in the + /// order in which they have been registered. +{ +public: + typedef TDelegate* DelegateHandle; + typedef SharedPtr<TDelegate> DelegatePtr; + typedef std::vector<DelegatePtr> Delegates; + typedef typename Delegates::iterator Iterator; + +public: + DefaultStrategy() + { + } + + DefaultStrategy(const DefaultStrategy& s): + _delegates(s._delegates) + { + } + + ~DefaultStrategy() + { + } + + void notify(const void* sender, TArgs& arguments) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + (*it)->notify(sender, arguments); + } + } + + DelegateHandle add(const TDelegate& delegate) + { + DelegatePtr pDelegate(static_cast<TDelegate*>(delegate.clone())); + _delegates.push_back(pDelegate); + return pDelegate.get(); + } + + void remove(const TDelegate& delegate) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if (delegate.equals(**it)) + { + (*it)->disable(); + _delegates.erase(it); + return; + } + } + } + + void remove(DelegateHandle delegateHandle) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if (*it == delegateHandle) + { + (*it)->disable(); + _delegates.erase(it); + return; + } + } + } + + DefaultStrategy& operator = (const DefaultStrategy& s) + { + if (this != &s) + { + _delegates = s._delegates; + } + return *this; + } + + void clear() + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + (*it)->disable(); + } + _delegates.clear(); + } + + bool empty() const + { + return _delegates.empty(); + } + +protected: + Delegates _delegates; +}; + + +template <class TDelegate> +class DefaultStrategy<void,TDelegate>: public NotificationStrategy<void, TDelegate> + /// Default notification strategy. + /// + /// Internally, a std::vector<> is used to store + /// delegate objects. Delegates are invoked in the + /// order in which they have been registered. +{ +public: + typedef TDelegate* DelegateHandle; + typedef SharedPtr<TDelegate> DelegatePtr; + typedef std::vector<DelegatePtr> Delegates; + typedef typename Delegates::iterator Iterator; + +public: + DefaultStrategy() + { + } + + DefaultStrategy(const DefaultStrategy& s): + _delegates(s._delegates) + { + } + + ~DefaultStrategy() + { + } + + void notify(const void* sender) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + (*it)->notify(sender); + } + } + + DelegateHandle add(const TDelegate& delegate) + { + DelegatePtr pDelegate(static_cast<TDelegate*>(delegate.clone())); + _delegates.push_back(pDelegate); + return pDelegate.get(); + } + + void remove(const TDelegate& delegate) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if (delegate.equals(**it)) + { + (*it)->disable(); + _delegates.erase(it); + return; + } + } + } + + void remove(DelegateHandle delegateHandle) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if (*it == delegateHandle) + { + (*it)->disable(); + _delegates.erase(it); + return; + } + } + } + + DefaultStrategy& operator = (const DefaultStrategy& s) + { + if (this != &s) + { + _delegates = s._delegates; + } + return *this; + } + + void clear() + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + (*it)->disable(); + } + _delegates.clear(); + } + + bool empty() const + { + return _delegates.empty(); + } + +protected: + Delegates _delegates; +}; + + +} // namespace Poco + + +#endif // Foundation_DefaultStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DeflatingStream.h b/contrib/libs/poco/Foundation/include/Poco/DeflatingStream.h new file mode 100644 index 0000000000..5c7b489ead --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DeflatingStream.h @@ -0,0 +1,201 @@ +// +// DeflatingStream.h +// +// Library: Foundation +// Package: Streams +// Module: ZLibStream +// +// Definition of the DeflatingStream class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DeflatingStream_INCLUDED +#define Foundation_DeflatingStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedStreamBuf.h" +#include <istream> +#include <ostream> +#if defined(POCO_UNBUNDLED) +#include <contrib/libs/zlib/zlib.h> +#else +#error #include "Poco/zlib.h" +#endif + + +namespace Poco { + + +class Foundation_API DeflatingStreamBuf: public BufferedStreamBuf + /// This is the streambuf class used by DeflatingInputStream and DeflatingOutputStream. + /// The actual work is delegated to zlib (see http://zlib.net). + /// Both zlib (deflate) streams and gzip streams are supported. + /// Output streams should always call close() to ensure + /// proper completion of compression. + /// A compression level (0 to 9) can be specified in the constructor. +{ +public: + enum StreamType + { + STREAM_ZLIB, /// Create a zlib header, use Adler-32 checksum. + STREAM_GZIP /// Create a gzip header, use CRC-32 checksum. + }; + + DeflatingStreamBuf(std::istream& istr, StreamType type, int level); + /// Creates a DeflatingStreamBuf for compressing data read + /// from the given input stream. + + DeflatingStreamBuf(std::istream& istr, int windowBits, int level); + /// Creates a DeflatingStreamBuf for compressing data read + /// from the given input stream. + /// + /// Please refer to the zlib documentation of deflateInit2() for a description + /// of the windowBits parameter. + + DeflatingStreamBuf(std::ostream& ostr, StreamType type, int level); + /// Creates a DeflatingStreamBuf for compressing data passed + /// through and forwarding it to the given output stream. + + DeflatingStreamBuf(std::ostream& ostr, int windowBits, int level); + /// Creates a DeflatingStreamBuf for compressing data passed + /// through and forwarding it to the given output stream. + /// + /// Please refer to the zlib documentation of deflateInit2() for a description + /// of the windowBits parameter. + + ~DeflatingStreamBuf(); + /// Destroys the DeflatingStreamBuf. + + int close(); + /// Finishes up the stream. + /// + /// Must be called when deflating to an output stream. + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + virtual int sync(); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024, + DEFLATE_BUFFER_SIZE = 32768 + }; + + std::istream* _pIstr; + std::ostream* _pOstr; + char* _buffer; + z_stream _zstr; + bool _eof; +}; + + +class Foundation_API DeflatingIOS: public virtual std::ios + /// The base class for DeflatingOutputStream and DeflatingInputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + DeflatingIOS(std::ostream& ostr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); + /// Creates a DeflatingIOS for compressing data passed + /// through and forwarding it to the given output stream. + + DeflatingIOS(std::ostream& ostr, int windowBits, int level); + /// Creates a DeflatingIOS for compressing data passed + /// through and forwarding it to the given output stream. + /// + /// Please refer to the zlib documentation of deflateInit2() for a description + /// of the windowBits parameter. + + DeflatingIOS(std::istream& istr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); + /// Creates a DeflatingIOS for compressing data read + /// from the given input stream. + + DeflatingIOS(std::istream& istr, int windowBits, int level); + /// Creates a DeflatingIOS for compressing data read + /// from the given input stream. + /// + /// Please refer to the zlib documentation of deflateInit2() for a description + /// of the windowBits parameter. + + ~DeflatingIOS(); + /// Destroys the DeflatingIOS. + + DeflatingStreamBuf* rdbuf(); + /// Returns a pointer to the underlying stream buffer. + +protected: + DeflatingStreamBuf _buf; +}; + + +class Foundation_API DeflatingOutputStream: public std::ostream, public DeflatingIOS + /// This stream compresses all data passing through it + /// using zlib's deflate algorithm. + /// After all data has been written to the stream, close() + /// must be called to ensure completion of compression. + /// Example: + /// std::ofstream ostr("data.gz", std::ios::binary); + /// DeflatingOutputStream deflater(ostr, DeflatingStreamBuf::STREAM_GZIP); + /// deflater << "Hello, world!" << std::endl; + /// deflater.close(); + /// ostr.close(); +{ +public: + DeflatingOutputStream(std::ostream& ostr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); + /// Creates a DeflatingOutputStream for compressing data passed + /// through and forwarding it to the given output stream. + + DeflatingOutputStream(std::ostream& ostr, int windowBits, int level); + /// Creates a DeflatingOutputStream for compressing data passed + /// through and forwarding it to the given output stream. + /// + /// Please refer to the zlib documentation of deflateInit2() for a description + /// of the windowBits parameter. + + ~DeflatingOutputStream(); + /// Destroys the DeflatingOutputStream. + + int close(); + /// Finishes up the stream. + /// + /// Must be called when deflating to an output stream. + +protected: + virtual int sync(); +}; + + +class Foundation_API DeflatingInputStream: public std::istream, public DeflatingIOS + /// This stream compresses all data passing through it + /// using zlib's deflate algorithm. +{ +public: + DeflatingInputStream(std::istream& istr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); + /// Creates a DeflatingIOS for compressing data read + /// from the given input stream. + + DeflatingInputStream(std::istream& istr, int windowBits, int level); + /// Creates a DeflatingIOS for compressing data read + /// from the given input stream. + /// + /// Please refer to the zlib documentation of deflateInit2() for a description + /// of the windowBits parameter. + + ~DeflatingInputStream(); + /// Destroys the DeflatingInputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_DeflatingStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Delegate.h b/contrib/libs/poco/Foundation/include/Poco/Delegate.h new file mode 100644 index 0000000000..b0b2c7615a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Delegate.h @@ -0,0 +1,452 @@ +// +// Delegate.h +// +// Library: Foundation +// Package: Events +// Module: Delegate +// +// Implementation of the Delegate template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Delegate_INCLUDED +#define Foundation_Delegate_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractDelegate.h" +#include "Poco/FunctionDelegate.h" +#include "Poco/Expire.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class TObj, class TArgs, bool withSender = true> +class Delegate: public AbstractDelegate<TArgs> +{ +public: + typedef void (TObj::*NotifyMethod)(const void*, TArgs&); + + Delegate(TObj* obj, NotifyMethod method): + _receiverObject(obj), + _receiverMethod(method) + { + } + + Delegate(const Delegate& delegate): + AbstractDelegate<TArgs>(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + ~Delegate() + { + } + + Delegate& operator = (const Delegate& delegate) + { + if (&delegate != this) + { + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + } + return *this; + } + + bool notify(const void* sender, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_receiverObject) + { + (_receiverObject->*_receiverMethod)(sender, arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const Delegate* pOtherDelegate = dynamic_cast<const Delegate*>(other.unwrap()); + return pOtherDelegate && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod; + } + + AbstractDelegate<TArgs>* clone() const + { + return new Delegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _receiverObject = 0; + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + Mutex _mutex; + +private: + Delegate(); +}; + + +template <class TObj, class TArgs> +class Delegate<TObj, TArgs, false>: public AbstractDelegate<TArgs> +{ +public: + typedef void (TObj::*NotifyMethod)(TArgs&); + + Delegate(TObj* obj, NotifyMethod method): + _receiverObject(obj), + _receiverMethod(method) + { + } + + Delegate(const Delegate& delegate): + AbstractDelegate<TArgs>(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + ~Delegate() + { + } + + Delegate& operator = (const Delegate& delegate) + { + if (&delegate != this) + { + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + } + return *this; + } + + bool notify(const void*, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_receiverObject) + { + (_receiverObject->*_receiverMethod)(arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const Delegate* pOtherDelegate = dynamic_cast<const Delegate*>(other.unwrap()); + return pOtherDelegate && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod; + } + + AbstractDelegate<TArgs>* clone() const + { + return new Delegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _receiverObject = 0; + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + Mutex _mutex; + +private: + Delegate(); +}; + + +template <class TObj, class TArgs> +inline Delegate<TObj, TArgs, true> delegate(TObj* pObj, void (TObj::*NotifyMethod)(const void*, TArgs&)) +{ + return Delegate<TObj, TArgs, true>(pObj, NotifyMethod); +} + + +template <class TObj, class TArgs> +inline Delegate<TObj, TArgs, false> delegate(TObj* pObj, void (TObj::*NotifyMethod)(TArgs&)) +{ + return Delegate<TObj, TArgs, false>(pObj, NotifyMethod); +} + + +template <class TObj, class TArgs> +inline Expire<TArgs> delegate(TObj* pObj, void (TObj::*NotifyMethod)(const void*, TArgs&), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<TArgs>(Delegate<TObj, TArgs, true>(pObj, NotifyMethod), expireMillisecs); +} + + +template <class TObj, class TArgs> +inline Expire<TArgs> delegate(TObj* pObj, void (TObj::*NotifyMethod)(TArgs&), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<TArgs>(Delegate<TObj, TArgs, false>(pObj, NotifyMethod), expireMillisecs); +} + + +template <class TArgs> +inline Expire<TArgs> delegate(void (*NotifyMethod)(const void*, TArgs&), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<TArgs>(FunctionDelegate<TArgs, true, true>(NotifyMethod), expireMillisecs); +} + + +template <class TArgs> +inline Expire<TArgs> delegate(void (*NotifyMethod)(void*, TArgs&), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<TArgs>(FunctionDelegate<TArgs, true, false>(NotifyMethod), expireMillisecs); +} + + +template <class TArgs> +inline Expire<TArgs> delegate(void (*NotifyMethod)(TArgs&), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<TArgs>(FunctionDelegate<TArgs, false>(NotifyMethod), expireMillisecs); +} + + +template <class TArgs> +inline FunctionDelegate<TArgs, true, true> delegate(void (*NotifyMethod)(const void*, TArgs&)) +{ + return FunctionDelegate<TArgs, true, true>(NotifyMethod); +} + + +template <class TArgs> +inline FunctionDelegate<TArgs, true, false> delegate(void (*NotifyMethod)(void*, TArgs&)) +{ + return FunctionDelegate<TArgs, true, false>(NotifyMethod); +} + + +template <class TArgs> +inline FunctionDelegate<TArgs, false> delegate(void (*NotifyMethod)(TArgs&)) +{ + return FunctionDelegate<TArgs, false>(NotifyMethod); +} + + +template <class TObj> +class Delegate<TObj,void,true>: public AbstractDelegate<void> +{ +public: + typedef void (TObj::*NotifyMethod)(const void*); + + Delegate(TObj* obj, NotifyMethod method): + _receiverObject(obj), + _receiverMethod(method) + { + } + + Delegate(const Delegate& delegate): + AbstractDelegate<void>(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + ~Delegate() + { + } + + Delegate& operator = (const Delegate& delegate) + { + if (&delegate != this) + { + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + } + return *this; + } + + bool notify(const void* sender) + { + Mutex::ScopedLock lock(_mutex); + if (_receiverObject) + { + (_receiverObject->*_receiverMethod)(sender); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const Delegate* pOtherDelegate = dynamic_cast<const Delegate*>(other.unwrap()); + return pOtherDelegate && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod; + } + + AbstractDelegate<void>* clone() const + { + return new Delegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _receiverObject = 0; + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + Mutex _mutex; + +private: + Delegate(); +}; + + +template <class TObj> +class Delegate<TObj, void, false>: public AbstractDelegate<void> +{ +public: + typedef void (TObj::*NotifyMethod)(); + + Delegate(TObj* obj, NotifyMethod method): + _receiverObject(obj), + _receiverMethod(method) + { + } + + Delegate(const Delegate& delegate): + AbstractDelegate<void>(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + ~Delegate() + { + } + + Delegate& operator = (const Delegate& delegate) + { + if (&delegate != this) + { + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + } + return *this; + } + + bool notify(const void*) + { + Mutex::ScopedLock lock(_mutex); + if (_receiverObject) + { + (_receiverObject->*_receiverMethod)(); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const Delegate* pOtherDelegate = dynamic_cast<const Delegate*>(other.unwrap()); + return pOtherDelegate && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod; + } + + AbstractDelegate<void>* clone() const + { + return new Delegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _receiverObject = 0; + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + Mutex _mutex; + +private: + Delegate(); +}; + + +template <class TObj> +inline Delegate<TObj, void, true> delegate(TObj* pObj, void (TObj::*NotifyMethod)(const void*)) +{ + return Delegate<TObj, void, true>(pObj, NotifyMethod); +} + + +template <class TObj> +inline Delegate<TObj, void, false> delegate(TObj* pObj, void (TObj::*NotifyMethod)()) +{ + return Delegate<TObj, void, false>(pObj, NotifyMethod); +} + + +template <class TObj> +inline Expire<void> delegate(TObj* pObj, void (TObj::*NotifyMethod)(const void*), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<void>(Delegate<TObj, void, true>(pObj, NotifyMethod), expireMillisecs); +} + + +template <class TObj> +inline Expire<void> delegate(TObj* pObj, void (TObj::*NotifyMethod)(), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<void>(Delegate<TObj, void, false>(pObj, NotifyMethod), expireMillisecs); +} + + +inline Expire<void> delegate(void (*NotifyMethod)(const void*), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<void>(FunctionDelegate<void, true, true>(NotifyMethod), expireMillisecs); +} + + +inline Expire<void> delegate(void (*NotifyMethod)(void*), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<void>(FunctionDelegate<void, true, false>(NotifyMethod), expireMillisecs); +} + + +inline Expire<void> delegate(void (*NotifyMethod)(), Timestamp::TimeDiff expireMillisecs) +{ + return Expire<void>(FunctionDelegate<void, false>(NotifyMethod), expireMillisecs); +} + + +inline FunctionDelegate<void, true, true> delegate(void (*NotifyMethod)(const void*)) +{ + return FunctionDelegate<void, true, true>(NotifyMethod); +} + + +inline FunctionDelegate<void, true, false> delegate(void (*NotifyMethod)(void*)) +{ + return FunctionDelegate<void, true, false>(NotifyMethod); +} + + +inline FunctionDelegate<void, false> delegate(void (*NotifyMethod)()) +{ + return FunctionDelegate<void, false>(NotifyMethod); +} + + +} // namespace Poco + + +#endif // Foundation_Delegate_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DigestEngine.h b/contrib/libs/poco/Foundation/include/Poco/DigestEngine.h new file mode 100644 index 0000000000..b22ab6d893 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DigestEngine.h @@ -0,0 +1,111 @@ +// +// DigestEngine.h +// +// Library: Foundation +// Package: Crypt +// Module: DigestEngine +// +// Definition of class DigestEngine. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DigestEngine_INCLUDED +#define Foundation_DigestEngine_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> + + +namespace Poco { + + +class Foundation_API DigestEngine + /// This class is an abstract base class + /// for all classes implementing a message + /// digest algorithm, like MD5Engine + /// and SHA1Engine. + /// Call update() repeatedly with data to + /// compute the digest from. When done, + /// call digest() to obtain the message + /// digest. +{ +public: + typedef std::vector<unsigned char> Digest; + + DigestEngine(); + virtual ~DigestEngine(); + + void update(const void* data, std::size_t length); + void update(char data); + void update(const std::string& data); + /// Updates the digest with the given data. + + virtual std::size_t digestLength() const = 0; + /// Returns the length of the digest in bytes. + + virtual void reset() = 0; + /// Resets the engine so that a new + /// digest can be computed. + + virtual const Digest& digest() = 0; + /// Finishes the computation of the digest and + /// returns the message digest. Resets the engine + /// and can thus only be called once for every digest. + /// The returned reference is valid until the next + /// time digest() is called, or the engine object is destroyed. + + static std::string digestToHex(const Digest& bytes); + /// Converts a message digest into a string of hexadecimal numbers. + + static Digest digestFromHex(const std::string& digest); + /// Converts a string created by digestToHex back to its Digest presentation + + static bool constantTimeEquals(const Digest& d1, const Digest& d2); + /// Compares two Digest values using a constant-time comparison + /// algorithm. This can be used to prevent timing attacks + /// (as discussed in <https://codahale.com/a-lesson-in-timing-attacks/>). + +protected: + virtual void updateImpl(const void* data, std::size_t length) = 0; + /// Updates the digest with the given data. Must be implemented + /// by subclasses. + +private: + DigestEngine(const DigestEngine&); + DigestEngine& operator = (const DigestEngine&); +}; + + +// +// inlines +// + + +inline void DigestEngine::update(const void* data, std::size_t length) +{ + updateImpl(data, length); +} + + +inline void DigestEngine::update(char data) +{ + updateImpl(&data, 1); +} + + +inline void DigestEngine::update(const std::string& data) +{ + updateImpl(data.data(), data.size()); +} + + +} // namespace Poco + + +#endif // Foundation_DigestEngine_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DigestStream.h b/contrib/libs/poco/Foundation/include/Poco/DigestStream.h new file mode 100644 index 0000000000..6976e01aa4 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DigestStream.h @@ -0,0 +1,100 @@ +// +// DigestStream.h +// +// Library: Foundation +// Package: Crypt +// Module: DigestStream +// +// Definition of classes DigestInputStream and DigestOutputStream. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DigestStream_INCLUDED +#define Foundation_DigestStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedStreamBuf.h" +#include "Poco/DigestEngine.h" +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API DigestBuf: public BufferedStreamBuf + /// This streambuf computes a digest of all data going + /// through it. +{ +public: + DigestBuf(DigestEngine& eng); + DigestBuf(DigestEngine& eng, std::istream& istr); + DigestBuf(DigestEngine& eng, std::ostream& ostr); + ~DigestBuf(); + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + void close(); + +private: + DigestEngine& _eng; + std::istream* _pIstr; + std::ostream* _pOstr; + static const int BUFFER_SIZE; +}; + + +class Foundation_API DigestIOS: public virtual std::ios + /// The base class for DigestInputStream and DigestOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + DigestIOS(DigestEngine& eng); + DigestIOS(DigestEngine& eng, std::istream& istr); + DigestIOS(DigestEngine& eng, std::ostream& ostr); + ~DigestIOS(); + DigestBuf* rdbuf(); + +protected: + DigestBuf _buf; +}; + + +class Foundation_API DigestInputStream: public DigestIOS, public std::istream + /// This istream computes a digest of + /// all the data passing through it, + /// using a DigestEngine. +{ +public: + DigestInputStream(DigestEngine& eng, std::istream& istr); + ~DigestInputStream(); +}; + + +class Foundation_API DigestOutputStream: public DigestIOS, public std::ostream + /// This ostream computes a digest of + /// all the data passing through it, + /// using a DigestEngine. + /// To ensure that all data has been incorporated + /// into the digest, call close() or flush() before + /// you obtain the digest from the digest engine. +{ +public: + DigestOutputStream(DigestEngine& eng); + DigestOutputStream(DigestEngine& eng, std::ostream& ostr); + ~DigestOutputStream(); + void close(); +}; + + +} // namespace Poco + + +#endif // Foundation_DigestStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator.h b/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator.h new file mode 100644 index 0000000000..c3cedf3f4e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator.h @@ -0,0 +1,153 @@ +// +// DirectoryIterator.h +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIterator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DirectoryIterator_INCLUDED +#define Foundation_DirectoryIterator_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/File.h" +#include "Poco/Path.h" + + +namespace Poco { + + +class DirectoryIteratorImpl; + + +class Foundation_API DirectoryIterator + /// The DirectoryIterator class is used to enumerate + /// all files in a directory. + /// + /// DirectoryIterator has some limitations: + /// * only forward iteration (++) is supported + /// * an iterator copied from another one will always + /// point to the same file as the original iterator, + /// even is the original iterator has been advanced + /// (all copies of an iterator share their state with + /// the original iterator) + /// * because of this you should only use the prefix + /// increment operator +{ +public: + DirectoryIterator(); + /// Creates the end iterator. + + DirectoryIterator(const std::string& path); + /// Creates a directory iterator for the given path. + + DirectoryIterator(const DirectoryIterator& iterator); + /// Creates a directory iterator for the given path. + + DirectoryIterator(const File& file); + /// Creates a directory iterator for the given file. + + DirectoryIterator(const Path& path); + /// Creates a directory iterator for the given path. + + virtual ~DirectoryIterator(); + /// Destroys the DirectoryIterator. + + const std::string& name() const; + /// Returns the current filename. + + const Path& path() const; + /// Returns the current path. + + DirectoryIterator& operator = (const DirectoryIterator& it); + DirectoryIterator& operator = (const File& file); + DirectoryIterator& operator = (const Path& path); + DirectoryIterator& operator = (const std::string& path); + + virtual DirectoryIterator& operator ++ (); // prefix + + //@ deprecated + DirectoryIterator operator ++ (int); // postfix + /// Please use the prefix increment operator instead. + + const File& operator * () const; + File& operator * (); + const File* operator -> () const; + File* operator -> (); + + bool operator == (const DirectoryIterator& iterator) const; + bool operator != (const DirectoryIterator& iterator) const; + +protected: + Path _path; + File _file; + +private: + DirectoryIteratorImpl* _pImpl; +}; + + +// +// inlines +// +inline const std::string& DirectoryIterator::name() const +{ + return _path.getFileName(); +} + + +inline const Path& DirectoryIterator::path() const +{ + return _path; +} + + +inline const File& DirectoryIterator::operator * () const +{ + return _file; +} + + +inline File& DirectoryIterator::operator * () +{ + return _file; +} + + +inline const File* DirectoryIterator::operator -> () const +{ + return &_file; +} + + +inline File* DirectoryIterator::operator -> () +{ + return &_file; +} + + +inline bool DirectoryIterator::operator == (const DirectoryIterator& iterator) const +{ + return name() == iterator.name(); +} + + +inline bool DirectoryIterator::operator != (const DirectoryIterator& iterator) const +{ + return name() != iterator.name(); +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DirectoryIteratorStrategy.h b/contrib/libs/poco/Foundation/include/Poco/DirectoryIteratorStrategy.h new file mode 100644 index 0000000000..4591f7c607 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DirectoryIteratorStrategy.h @@ -0,0 +1,92 @@ +// +// RecursiveDirectoryIteratorStategies.h +// +// Library: Foundation +// Package: Filesystem +// Module: RecursiveDirectoryIterator +// +// Definitions of the RecursiveDirectoryIterator stategy classes. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RecursiveDirectoryIteratorStrategy_INCLUDED +#define Foundation_RecursiveDirectoryIteratorStrategy_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DirectoryIterator.h" +#include <stack> +#include <queue> +#include <functional> + + +namespace Poco { + + +class Foundation_API TraverseBase +{ +public: + typedef std::stack<DirectoryIterator> Stack; + typedef std::function<UInt16(const Stack&)> DepthFunPtr; + + enum + { + D_INFINITE = 0 /// Special value for infinite traverse depth. + }; + + TraverseBase(DepthFunPtr depthDeterminer, UInt16 maxDepth = D_INFINITE); + +protected: + bool isFiniteDepth(); + bool isDirectory(Poco::File& file); + + DepthFunPtr _depthDeterminer; + UInt16 _maxDepth; + DirectoryIterator _itEnd; + +private: + TraverseBase(); + TraverseBase(const TraverseBase&); + TraverseBase& operator=(const TraverseBase&); +}; + + +class Foundation_API ChildrenFirstTraverse: public TraverseBase +{ +public: + ChildrenFirstTraverse(DepthFunPtr depthDeterminer, UInt16 maxDepth = D_INFINITE); + + const std::string next(Stack* itStack, bool* isFinished); + +private: + ChildrenFirstTraverse(); + ChildrenFirstTraverse(const ChildrenFirstTraverse&); + ChildrenFirstTraverse& operator=(const ChildrenFirstTraverse&); +}; + + +class Foundation_API SiblingsFirstTraverse: public TraverseBase +{ +public: + SiblingsFirstTraverse(DepthFunPtr depthDeterminer, UInt16 maxDepth = D_INFINITE); + + const std::string next(Stack* itStack, bool* isFinished); + +private: + SiblingsFirstTraverse(); + SiblingsFirstTraverse(const SiblingsFirstTraverse&); + SiblingsFirstTraverse& operator=(const SiblingsFirstTraverse&); + + std::stack<std::queue<std::string> > _dirsStack; +}; + + +} // namespace Poco + + +#endif // Foundation_RecursiveDirectoryIteratorStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_UNIX.h b/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_UNIX.h new file mode 100644 index 0000000000..d21f711921 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_UNIX.h @@ -0,0 +1,72 @@ +// +// DirectoryIterator_UNIX.h +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIteratorImpl class for UNIX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DirectoryIterator_UNIX_INCLUDED +#define Foundation_DirectoryIterator_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include <dirent.h> + + +namespace Poco { + + +class Foundation_API DirectoryIteratorImpl +{ +public: + DirectoryIteratorImpl(const std::string& path); + ~DirectoryIteratorImpl(); + + void duplicate(); + void release(); + + const std::string& get() const; + const std::string& next(); + +private: + DIR* _pDir; + std::string _current; + int _rc; +}; + + +// +// inlines +// +const std::string& DirectoryIteratorImpl::get() const +{ + return _current; +} + + +inline void DirectoryIteratorImpl::duplicate() +{ + ++_rc; +} + + +inline void DirectoryIteratorImpl::release() +{ + if (--_rc == 0) + delete this; +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_WIN32.h new file mode 100644 index 0000000000..068cac3675 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_WIN32.h @@ -0,0 +1,73 @@ +// +// DirectoryIterator_WIN32.h +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIteratorImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DirectoryIterator_WIN32_INCLUDED +#define Foundation_DirectoryIterator_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API DirectoryIteratorImpl +{ +public: + DirectoryIteratorImpl(const std::string& path); + ~DirectoryIteratorImpl(); + + void duplicate(); + void release(); + + const std::string& get() const; + const std::string& next(); + +private: + HANDLE _fh; + WIN32_FIND_DATA _fd; + std::string _current; + int _rc; +}; + + +// +// inlines +// +const std::string& DirectoryIteratorImpl::get() const +{ + return _current; +} + + +inline void DirectoryIteratorImpl::duplicate() +{ + ++_rc; +} + + +inline void DirectoryIteratorImpl::release() +{ + if (--_rc == 0) + delete this; +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_WIN32U.h new file mode 100644 index 0000000000..496842c7f9 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DirectoryIterator_WIN32U.h @@ -0,0 +1,73 @@ +// +// DirectoryIterator_WIN32U.h +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIteratorImpl class for WIN32. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DirectoryIterator_WIN32U_INCLUDED +#define Foundation_DirectoryIterator_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API DirectoryIteratorImpl +{ +public: + DirectoryIteratorImpl(const std::string& path); + ~DirectoryIteratorImpl(); + + void duplicate(); + void release(); + + const std::string& get() const; + const std::string& next(); + +private: + HANDLE _fh; + WIN32_FIND_DATAW _fd; + std::string _current; + int _rc; +}; + + +// +// inlines +// +const std::string& DirectoryIteratorImpl::get() const +{ + return _current; +} + + +inline void DirectoryIteratorImpl::duplicate() +{ + ++_rc; +} + + +inline void DirectoryIteratorImpl::release() +{ + if (--_rc == 0) + delete this; +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DirectoryWatcher.h b/contrib/libs/poco/Foundation/include/Poco/DirectoryWatcher.h new file mode 100644 index 0000000000..6e3a492fd5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DirectoryWatcher.h @@ -0,0 +1,232 @@ +// +// DirectoryWatcher.h +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryWatcher +// +// Definition of the DirectoryWatcher class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DirectoryWatcher_INCLUDED +#define Foundation_DirectoryWatcher_INCLUDED + + +#include "Poco/Foundation.h" + + +#ifndef POCO_NO_INOTIFY + + +#include "Poco/File.h" +#include "Poco/BasicEvent.h" +#include "Poco/Runnable.h" +#include "Poco/Thread.h" +#include "Poco/AtomicCounter.h" + + +namespace Poco { + + +class DirectoryWatcherStrategy; + + +class Foundation_API DirectoryWatcher: protected Runnable + /// This class is used to get notifications about changes + /// to the filesystem, more specifically, to a specific + /// directory. Changes to a directory are reported via + /// events. + /// + /// A thread will be created that watches the specified + /// directory for changes. Events are reported in the context + /// of this thread. + /// + /// Note that changes to files in subdirectories of the watched + /// directory are not reported. Separate DirectoryWatcher objects + /// must be created for these directories if they should be watched. + /// + /// Changes to file attributes are not reported. + /// + /// On Windows, this class is implemented using FindFirstChangeNotification()/FindNextChangeNotification(). + /// On Linux, this class is implemented using inotify. + /// On FreeBSD and Darwin (Mac OS X, iOS), this class uses kevent/kqueue. + /// On all other platforms, the watched directory is periodically scanned + /// for changes. This can negatively affect performance if done too often. + /// Therefore, the interval in which scans are done can be specified in + /// the constructor. Note that periodic scanning will also be done on FreeBSD + /// and Darwin if events for changes to files (DW_ITEM_MODIFIED) are enabled. + /// + /// DW_ITEM_MOVED_FROM and DW_ITEM_MOVED_TO events will only be reported + /// on Linux. On other platforms, a file rename or move operation + /// will be reported via a DW_ITEM_REMOVED and a DW_ITEM_ADDED event. + /// The order of these two events is not defined. + /// + /// An event mask can be specified to enable only certain events. +{ +public: + enum DirectoryEventType + { + DW_ITEM_ADDED = 1, + /// A new item has been created and added to the directory. + + DW_ITEM_REMOVED = 2, + /// An item has been removed from the directory. + + DW_ITEM_MODIFIED = 4, + /// An item has been modified. + + DW_ITEM_MOVED_FROM = 8, + /// An item has been renamed or moved. This event delivers the old name. + + DW_ITEM_MOVED_TO = 16 + /// An item has been renamed or moved. This event delivers the new name. + }; + + enum DirectoryEventMask + { + DW_FILTER_ENABLE_ALL = 31, + /// Enables all event types. + + DW_FILTER_DISABLE_ALL = 0 + /// Disables all event types. + }; + + enum + { + DW_DEFAULT_SCAN_INTERVAL = 5 /// Default scan interval for platforms that don't provide a native notification mechanism. + }; + + struct DirectoryEvent + { + DirectoryEvent(const File& f, DirectoryEventType ev): + item(f), + event(ev) + { + } + + const File& item; /// The directory or file that has been changed. + DirectoryEventType event; /// The kind of event. + }; + + BasicEvent<const DirectoryEvent> itemAdded; + /// Fired when a file or directory has been created or added to the directory. + + BasicEvent<const DirectoryEvent> itemRemoved; + /// Fired when a file or directory has been removed from the directory. + + BasicEvent<const DirectoryEvent> itemModified; + /// Fired when a file or directory has been modified. + + BasicEvent<const DirectoryEvent> itemMovedFrom; + /// Fired when a file or directory has been renamed. This event delivers the old name. + + BasicEvent<const DirectoryEvent> itemMovedTo; + /// Fired when a file or directory has been moved. This event delivers the new name. + + BasicEvent<const Exception> scanError; + /// Fired when an error occurs while scanning for changes. + + DirectoryWatcher(const std::string& path, int eventMask = DW_FILTER_ENABLE_ALL, int scanInterval = DW_DEFAULT_SCAN_INTERVAL); + /// Creates a DirectoryWatcher for the directory given in path. + /// To enable only specific events, an eventMask can be specified by + /// OR-ing the desired event IDs (e.g., DW_ITEM_ADDED | DW_ITEM_MODIFIED). + /// On platforms where no native filesystem notifications are available, + /// scanInterval specifies the interval in seconds between scans + /// of the directory. + + DirectoryWatcher(const File& directory, int eventMask = DW_FILTER_ENABLE_ALL, int scanInterval = DW_DEFAULT_SCAN_INTERVAL); + /// Creates a DirectoryWatcher for the specified directory + /// To enable only specific events, an eventMask can be specified by + /// OR-ing the desired event IDs (e.g., DW_ITEM_ADDED | DW_ITEM_MODIFIED). + /// On platforms where no native filesystem notifications are available, + /// scanInterval specifies the interval in seconds between scans + /// of the directory. + + ~DirectoryWatcher(); + /// Destroys the DirectoryWatcher. + + void suspendEvents(); + /// Suspends sending of events. Can be called multiple times, but every + /// call to suspendEvent() must be matched by a call to resumeEvents(). + + void resumeEvents(); + /// Resumes events, after they have been suspended with a call to suspendEvents(). + + bool eventsSuspended() const; + /// Returns true iff events are suspended. + + int eventMask() const; + /// Returns the value of the eventMask passed to the constructor. + + int scanInterval() const; + /// Returns the scan interval in seconds. + + const File& directory() const; + /// Returns the directory being watched. + + bool supportsMoveEvents() const; + /// Returns true iff the platform supports DW_ITEM_MOVED_FROM/itemMovedFrom and + /// DW_ITEM_MOVED_TO/itemMovedTo events. + +protected: + void init(); + void stop(); + void run(); + +private: + DirectoryWatcher(); + DirectoryWatcher(const DirectoryWatcher&); + DirectoryWatcher& operator = (const DirectoryWatcher&); + + Thread _thread; + File _directory; + int _eventMask; + AtomicCounter _eventsSuspended; + int _scanInterval; + DirectoryWatcherStrategy* _pStrategy; +}; + + +// +// inlines +// + + +inline bool DirectoryWatcher::eventsSuspended() const +{ + return _eventsSuspended.value() > 0; +} + + +inline int DirectoryWatcher::eventMask() const +{ + return _eventMask; +} + + +inline int DirectoryWatcher::scanInterval() const +{ + return _scanInterval; +} + + +inline const File& DirectoryWatcher::directory() const +{ + return _directory; +} + + +} // namespace Poco + + +#endif // POCO_NO_INOTIFY + + +#endif // Foundation_DirectoryWatcher_INCLUDED + diff --git a/contrib/libs/poco/Foundation/include/Poco/Dynamic/Pair.h b/contrib/libs/poco/Foundation/include/Poco/Dynamic/Pair.h new file mode 100644 index 0000000000..c64eececeb --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Dynamic/Pair.h @@ -0,0 +1,412 @@ +// +// Pair.h +// +// Library: Foundation +// Package: Dynamic +// Module: Pair +// +// Definition of the Pair class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Pair_INCLUDED +#define Foundation_Pair_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Dynamic/Var.h" +#include "Poco/Dynamic/VarHolder.h" +#include <utility> + + +namespace Poco { +namespace Dynamic { + + +template <typename K> +class Pair + /// Pair allows to define a pair of values. +{ +public: + typedef typename std::pair<K, Var> Data; + + Pair(): _data() + /// Creates an empty Pair + { + } + + Pair(const Pair& other): _data(other._data) + /// Creates the Pair from another pair. + { + } + + Pair(const Data& val): _data(val) + /// Creates the Pair from the given value. + { + } + + template <typename T> + Pair(const std::pair<K, T>& val): _data(std::make_pair(val.first, val.second)) + /// Creates Pair form standard pair. + { + } + + template <typename T> + Pair(const K& first, const T& second): _data(std::make_pair(first, second)) + /// Creates pair from two values. + { + } + + virtual ~Pair() + /// Destroys the Pair. + { + } + + Pair& swap(Pair& other) + /// Swaps the content of the two Pairs. + { + std::swap(_data, other._data); + return *this; + } + + Pair& operator = (const Pair& other) + /// Copy constructs Pair from another pair. + { + Pair(other).swap(*this); + return *this; + } + + inline const K& first() const + /// Returns the first member of the pair. + { + return _data.first; + } + + inline const Var& second() const + /// Returns the second member of the pair. + { + return _data.second; + } + + std::string toString() + { + std::string str; + Var(*this).convert<std::string>(str); + return str; + } + +private: + Data _data; +}; + + +template <> +class VarHolderImpl<Pair<std::string> >: public VarHolder +{ +public: + VarHolderImpl(const Pair<std::string>& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Pair<std::string>); + } + + void convert(Int8& val) const + { + throw BadCastException("Cannot cast Pair type to Int8"); + } + + void convert(Int16& val) const + { + throw BadCastException("Cannot cast Pair type to Int16"); + } + + void convert(Int32& val) const + { + throw BadCastException("Cannot cast Pair type to Int32"); + } + + void convert(Int64& val) const + { + throw BadCastException("Cannot cast Pair type to Int64"); + } + + void convert(UInt8& val) const + { + throw BadCastException("Cannot cast Pair type to UInt8"); + } + + void convert(UInt16& val) const + { + throw BadCastException("Cannot cast Pair type to UInt16"); + } + + void convert(UInt32& val) const + { + throw BadCastException("Cannot cast Pair type to UInt32"); + } + + void convert(UInt64& val) const + { + throw BadCastException("Cannot cast Pair type to UInt64"); + } + + void convert(bool& val) const + { + throw BadCastException("Cannot cast Pair type to bool"); + } + + void convert(float& val) const + { + throw BadCastException("Cannot cast Pair type to float"); + } + + void convert(double& val) const + { + throw BadCastException("Cannot cast Pair type to double"); + } + + void convert(char& val) const + { + throw BadCastException("Cannot cast Pair type to char"); + } + + void convert(std::string& val) const + { + // Serialize in JSON format: equals an object + // JSON format definition: { string ':' value } string:value pair n-times, sep. by ',' + val.append("{ "); + Var key(_val.first()); + Impl::appendJSONKey(val, key); + val.append(" : "); + Impl::appendJSONValue(val, _val.second()); + val.append(" }"); + } + + void convert(Poco::DateTime&) const + { + throw BadCastException("Pair -> Poco::DateTime"); + } + + void convert(Poco::LocalDateTime&) const + { + throw BadCastException("Pair -> Poco::LocalDateTime"); + } + + void convert(Poco::Timestamp&) const + { + throw BadCastException("Pair -> Poco::Timestamp"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Pair<std::string>& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + Pair<std::string> _val; +}; + + +template <> +class VarHolderImpl<Pair<int> >: public VarHolder +{ +public: + VarHolderImpl(const Pair<int>& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Pair<int>); + } + + void convert(Int8& val) const + { + throw BadCastException("Cannot cast Pair type to Int8"); + } + + void convert(Int16& val) const + { + throw BadCastException("Cannot cast Pair type to Int16"); + } + + void convert(Int32& val) const + { + throw BadCastException("Cannot cast Pair type to Int32"); + } + + void convert(Int64& val) const + { + throw BadCastException("Cannot cast Pair type to Int64"); + } + + void convert(UInt8& val) const + { + throw BadCastException("Cannot cast Pair type to UInt8"); + } + + void convert(UInt16& val) const + { + throw BadCastException("Cannot cast Pair type to UInt16"); + } + + void convert(UInt32& val) const + { + throw BadCastException("Cannot cast Pair type to UInt32"); + } + + void convert(UInt64& val) const + { + throw BadCastException("Cannot cast Pair type to UInt64"); + } + + void convert(bool& val) const + { + throw BadCastException("Cannot cast Pair type to bool"); + } + + void convert(float& val) const + { + throw BadCastException("Cannot cast Pair type to float"); + } + + void convert(double& val) const + { + throw BadCastException("Cannot cast Pair type to double"); + } + + void convert(char& val) const + { + throw BadCastException("Cannot cast Pair type to char"); + } + + void convert(std::string& val) const + { + // Serialize in JSON format: equals an object + // JSON format definition: { string ':' value } string:value pair n-times, sep. by ',' + val.append("{ "); + Var key(_val.first()); + Impl::appendJSONKey(val, key); + val.append(" : "); + Impl::appendJSONValue(val, _val.second()); + val.append(" }"); + } + + void convert(Poco::DateTime&) const + { + throw BadCastException("Pair -> Poco::DateTime"); + } + + void convert(Poco::LocalDateTime&) const + { + throw BadCastException("Pair -> Poco::LocalDateTime"); + } + + void convert(Poco::Timestamp&) const + { + throw BadCastException("Pair -> Poco::Timestamp"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Pair<int>& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + Pair<int> _val; +}; + + +} // namespace Dynamic + + +} // namespace Poco + + +#endif // Foundation_Pair_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Dynamic/Struct.h b/contrib/libs/poco/Foundation/include/Poco/Dynamic/Struct.h new file mode 100644 index 0000000000..fc9d57d55e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Dynamic/Struct.h @@ -0,0 +1,567 @@ +// +// Struct.h +// +// Library: Foundation +// Package: Dynamic +// Module: Struct +// +// Definition of the Struct class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Struct_INCLUDED +#define Foundation_Struct_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Dynamic/Var.h" +#include "Poco/Dynamic/VarHolder.h" +#include "Poco/SharedPtr.h" +#include <map> +#include <set> + + +namespace Poco { +namespace Dynamic { + + +template <typename K> +class Struct + /// Struct allows to define a named collection of Var objects. +{ +public: + typedef typename std::map<K, Var> Data; + typedef typename std::set<K> NameSet; + typedef typename Data::iterator Iterator; + typedef typename Data::const_iterator ConstIterator; + typedef typename Struct<K>::Data::value_type ValueType; + typedef typename Struct<K>::Data::size_type SizeType; + typedef typename std::pair<typename Struct<K>::Iterator, bool> InsRetVal; + typedef typename Poco::SharedPtr<Struct<K> > Ptr; + + Struct(): _data() + /// Creates an empty Struct + { + } + + Struct(const Data& val): _data(val) + /// Creates the Struct from the given value. + { + } + + template <typename T> + Struct(const std::map<K, T>& val) + { + typedef typename std::map<K, T>::const_iterator MapConstIterator; + + MapConstIterator it = val.begin(); + MapConstIterator itEnd = val.end(); + for (; it != itEnd; ++it) _data.insert(ValueType(it->first, Var(it->second))); + } + + virtual ~Struct() + /// Destroys the Struct. + { + } + + inline Var& operator [] (const K& name) + /// Returns the Var with the given name, creates an entry if not found. + { + return _data[name]; + } + + const Var& operator [] (const K& name) const + /// Returns the Var with the given name, throws a + /// NotFoundException if the data member is not found. + { + ConstIterator it = find(name); + if (it == end()) throw NotFoundException(name); + return it->second; + } + + inline bool contains(const K& name) const + /// Returns true if the Struct contains a member with the given name + { + return find(name) != end(); + } + + inline Iterator find(const K& name) + /// Returns an iterator, pointing to the <name,Var> pair containing + /// the element, or it returns end() if the member was not found + { + return _data.find(name); + } + + inline ConstIterator find(const K& name) const + /// Returns a const iterator, pointing to the <name,Var> pair containing + /// the element, or it returns end() if the member was not found + { + return _data.find(name); + } + + inline Iterator end() + /// Returns the end iterator for the Struct + { + return _data.end(); + } + + inline ConstIterator end() const + /// Returns the end const iterator for the Struct + { + return _data.end(); + } + + inline Iterator begin() + /// Returns the begin iterator for the Struct + { + return _data.begin(); + } + + inline ConstIterator begin() const + /// Returns the begin const iterator for the Struct + { + return _data.begin(); + } + + template <typename T> + inline InsRetVal insert(const K& key, const T& value) + /// Inserts a <name, Var> pair into the Struct, + /// returns a pair containing the iterator and a boolean which + /// indicates success or not (is true, when insert succeeded, false, + /// when already another element was present, in this case Iterator + /// points to that other element) + { + // fix: SunPro C++ is silly ... + ValueType valueType(key, value); + return insert(valueType); + } + + inline InsRetVal insert(const ValueType& aPair) + /// Inserts a <name, Var> pair into the Struct, + /// returns a pair containing the iterator and a boolean which + /// indicates success or not (is true, when insert succeeded, false, + /// when already another element was present, in this case Iterator + /// points to that other element) + { + return _data.insert(aPair); + } + + inline SizeType erase(const K& key) + /// Erases the element if found, returns number of elements deleted + { + return _data.erase(key); + } + + inline void erase(Iterator& it) + /// Erases the element at the given position + { + _data.erase(it); + } + + inline bool empty() const + /// Returns true if the Struct doesn't contain any members + { + return _data.empty(); + } + + inline void clear() + /// Clears the Struct contents + { + _data.clear(); + } + + SizeType size() const + /// Returns the number of members the Struct contains + { + return _data.size(); + } + + inline NameSet members() const + /// Returns a sorted collection containing all member names + { + NameSet keys; + ConstIterator it = begin(); + ConstIterator itEnd = end(); + for (; it != itEnd; ++it) keys.insert(it->first); + return keys; + } + + std::string toString() + { + std::string str; + Var(*this).convert<std::string>(str); + return str; + } + +private: + Data _data; +}; + + +template <> +class VarHolderImpl<Struct<std::string> >: public VarHolder +{ +public: + VarHolderImpl(const Struct<std::string>& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Struct<std::string>); + } + + void convert(Int8&) const + { + throw BadCastException("Cannot cast Struct type to Int8"); + } + + void convert(Int16&) const + { + throw BadCastException("Cannot cast Struct type to Int16"); + } + + void convert(Int32&) const + { + throw BadCastException("Cannot cast Struct type to Int32"); + } + + void convert(Int64&) const + { + throw BadCastException("Cannot cast Struct type to Int64"); + } + + void convert(UInt8&) const + { + throw BadCastException("Cannot cast Struct type to UInt8"); + } + + void convert(UInt16&) const + { + throw BadCastException("Cannot cast Struct type to UInt16"); + } + + void convert(UInt32&) const + { + throw BadCastException("Cannot cast Struct type to UInt32"); + } + + void convert(UInt64&) const + { + throw BadCastException("Cannot cast Struct type to UInt64"); + } + + void convert(bool&) const + { + throw BadCastException("Cannot cast Struct type to bool"); + } + + void convert(float&) const + { + throw BadCastException("Cannot cast Struct type to float"); + } + + void convert(double&) const + { + throw BadCastException("Cannot cast Struct type to double"); + } + + void convert(char&) const + { + throw BadCastException("Cannot cast Struct type to char"); + } + + void convert(std::string& val) const + { + val.append("{ "); + Struct<std::string>::ConstIterator it = _val.begin(); + Struct<std::string>::ConstIterator itEnd = _val.end(); + if (!_val.empty()) + { + Var key(it->first); + Impl::appendJSONKey(val, key); + val.append(" : "); + Impl::appendJSONValue(val, it->second); + ++it; + } + for (; it != itEnd; ++it) + { + val.append(", "); + Var key(it->first); + Impl::appendJSONKey(val, key); + val.append(" : "); + Impl::appendJSONValue(val, it->second); + } + val.append(" }"); + } + + void convert(Poco::DateTime&) const + { + throw BadCastException("Struct -> Poco::DateTime"); + } + + void convert(Poco::LocalDateTime&) const + { + throw BadCastException("Struct -> Poco::LocalDateTime"); + } + + void convert(Poco::Timestamp&) const + { + throw BadCastException("Struct -> Poco::Timestamp"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Struct<std::string>& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return true; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isString() const + { + return false; + } + + std::size_t size() const + { + return _val.size(); + } + + Var& operator [] (const std::string& name) + { + return _val[name]; + } + + const Var& operator [] (const std::string& name) const + { + return _val[name]; + } + +private: + Struct<std::string> _val; +}; + + +template <> +class VarHolderImpl<Struct<int> >: public VarHolder +{ +public: + VarHolderImpl(const Struct<int>& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Struct<int>); + } + + void convert(Int8&) const + { + throw BadCastException("Cannot cast Struct type to Int8"); + } + + void convert(Int16&) const + { + throw BadCastException("Cannot cast Struct type to Int16"); + } + + void convert(Int32&) const + { + throw BadCastException("Cannot cast Struct type to Int32"); + } + + void convert(Int64&) const + { + throw BadCastException("Cannot cast Struct type to Int64"); + } + + void convert(UInt8&) const + { + throw BadCastException("Cannot cast Struct type to UInt8"); + } + + void convert(UInt16&) const + { + throw BadCastException("Cannot cast Struct type to UInt16"); + } + + void convert(UInt32&) const + { + throw BadCastException("Cannot cast Struct type to UInt32"); + } + + void convert(UInt64&) const + { + throw BadCastException("Cannot cast Struct type to UInt64"); + } + + void convert(bool&) const + { + throw BadCastException("Cannot cast Struct type to bool"); + } + + void convert(float&) const + { + throw BadCastException("Cannot cast Struct type to float"); + } + + void convert(double&) const + { + throw BadCastException("Cannot cast Struct type to double"); + } + + void convert(char&) const + { + throw BadCastException("Cannot cast Struct type to char"); + } + + void convert(std::string& val) const + { + val.append("{ "); + Struct<int>::ConstIterator it = _val.begin(); + Struct<int>::ConstIterator itEnd = _val.end(); + if (!_val.empty()) + { + Var key(it->first); + Impl::appendJSONKey(val, key); + val.append(" : "); + Impl::appendJSONValue(val, it->second); + ++it; + } + for (; it != itEnd; ++it) + { + val.append(", "); + Var key(it->first); + Impl::appendJSONKey(val, key); + val.append(" : "); + Impl::appendJSONValue(val, it->second); + } + val.append(" }"); + } + + void convert(Poco::DateTime&) const + { + throw BadCastException("Struct -> Poco::DateTime"); + } + + void convert(Poco::LocalDateTime&) const + { + throw BadCastException("Struct -> Poco::LocalDateTime"); + } + + void convert(Poco::Timestamp&) const + { + throw BadCastException("Struct -> Poco::Timestamp"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Struct<int>& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return true; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isString() const + { + return false; + } + + std::size_t size() const + { + return _val.size(); + } + + Var& operator [] (int name) + { + return _val[name]; + } + + const Var& operator [] (int name) const + { + return _val[name]; + } + +private: + Struct<int> _val; +}; + + +} // namespace Dynamic + + +typedef Dynamic::Struct<std::string> DynamicStruct; + + +} // namespace Poco + + +#endif // Foundation_Struct_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Dynamic/Var.h b/contrib/libs/poco/Foundation/include/Poco/Dynamic/Var.h new file mode 100644 index 0000000000..bd06afe54b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Dynamic/Var.h @@ -0,0 +1,2228 @@ +// +// Var.h +// +// Library: Foundation +// Package: Dynamic +// Module: Var +// +// Definition of the Var class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Var_INCLUDED +#define Foundation_Var_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Format.h" +#include "Poco/SharedPtr.h" +#include "Poco/Dynamic/VarHolder.h" +#include "Poco/Dynamic/VarIterator.h" +#include <typeinfo> + + +namespace Poco { +namespace Dynamic { + + +template <typename T> +class Struct; + + +class Foundation_API Var + /// Var allows to store data of different types and to convert between these types transparently. + /// Var puts forth the best effort to provide intuitive and reasonable conversion semantics and prevent + /// unexpected data loss, particularly when performing narrowing or signedness conversions of numeric data types. + /// + /// An attempt to convert or extract from a non-initialized ("empty") Var variable shall result + /// in an exception being thrown. + /// + /// Loss of signedness is not allowed for numeric values. This means that if an attempt is made to convert + /// the internal value which is a negative signed integer to an unsigned integer type storage, a RangeException is thrown. + /// Overflow is not allowed, so if the internal value is a larger number than the target numeric type size can accommodate, + /// a RangeException is thrown. + /// + /// Precision loss, such as in conversion from floating-point types to integers or from double to float on platforms + /// where they differ in size (provided internal actual value fits in float min/max range), is allowed. + /// + /// String truncation is allowed -- it is possible to convert between string and character when string length is + /// greater than 1. An empty string gets converted to the char '\0', a non-empty string is truncated to the first character. + /// + /// Boolean conversion is performed as follows: + /// + /// A string value "false" (not case sensitive), "0" or "" (empty string) can be converted to a boolean value false, + /// any other string not being false by the above criteria evaluates to true (e.g: "hi" -> true). + /// Integer 0 values are false, everything else is true. + /// Floating point values equal to the minimal FP representation on a given platform are false, everything else is true. + /// + /// Arithmetic operations with POD types as well as between Var's are supported, subject to following + /// limitations: + /// + /// - for std::string and const char* values, only '+' and '+=' operations are supported + /// + /// - for integral and floating point numeric values, following operations are supported: + /// '+', '+=', '-', '-=', '*', '*=' , '/' and '/=' + /// + /// - for integral values, following operations are supported: + /// prefix and postfix increment (++) and decrement (--) + /// + /// - for all other types, InvalidArgumentException is thrown upon attempt of an arithmetic operation + /// + /// A Var can be created from and converted to a value of any type for which a specialization of + /// VarHolderImpl is available. For supported types, see VarHolder documentation. +{ +public: + typedef SharedPtr<Var> Ptr; + typedef Poco::Dynamic::VarIterator Iterator; + typedef const VarIterator ConstIterator; + + Var(); + /// Creates an empty Var. + + template <typename T> + Var(const T& val) + /// Creates the Var from the given value. +#ifdef POCO_NO_SOO + : _pHolder(new VarHolderImpl<T>(val)) + { + } +#else + { + construct(val); + } +#endif + + Var(const char* pVal); + // Convenience constructor for const char* which gets mapped to a std::string internally, i.e. pVal is deep-copied. + + Var(const Var& other); + /// Copy constructor. + + ~Var(); + /// Destroys the Var. + + void swap(Var& other); + /// Swaps the content of the this Var with the other Var. + + ConstIterator begin() const; + /// Returns the const Var iterator. + + ConstIterator end() const; + /// Returns the const Var iterator. + + Iterator begin(); + /// Returns the Var iterator. + + Iterator end(); + /// Returns the Var iterator. + + template <typename T> + void convert(T& val) const + /// Invoke this method to perform a safe conversion. + /// + /// Example usage: + /// Var any("42"); + /// int i; + /// any.convert(i); + /// + /// Throws a RangeException if the value does not fit + /// into the result variable. + /// Throws a NotImplementedException if conversion is + /// not available for the given type. + /// Throws InvalidAccessException if Var is empty. + { + VarHolder* pHolder = content(); + + if (!pHolder) + throw InvalidAccessException("Can not convert empty value."); + + pHolder->convert(val); + } + + template <typename T> + T convert() const + /// Invoke this method to perform a safe conversion. + /// + /// Example usage: + /// Var any("42"); + /// int i = any.convert<int>(); + /// + /// Throws a RangeException if the value does not fit + /// into the result variable. + /// Throws a NotImplementedException if conversion is + /// not available for the given type. + /// Throws InvalidAccessException if Var is empty. + { + VarHolder* pHolder = content(); + + if (!pHolder) + throw InvalidAccessException("Can not convert empty value."); + + if (typeid(T) == pHolder->type()) return extract<T>(); + + T result; + pHolder->convert(result); + return result; + } + + template <typename T> + operator T () const + /// Safe conversion operator for implicit type + /// conversions. If the requested type T is same as the + /// type being held, the operation performed is direct + /// extraction, otherwise it is the conversion of the value + /// from type currently held to the one requested. + /// + /// Throws a RangeException if the value does not fit + /// into the result variable. + /// Throws a NotImplementedException if conversion is + /// not available for the given type. + /// Throws InvalidAccessException if Var is empty. + { + VarHolder* pHolder = content(); + + if (!pHolder) + throw InvalidAccessException("Can not convert empty value."); + + if (typeid(T) == pHolder->type()) + return extract<T>(); + else + { + T result; + pHolder->convert(result); + return result; + } + } + + template <typename T> + const T& extract() const + /// Returns a const reference to the actual value. + /// + /// Must be instantiated with the exact type of + /// the stored value, otherwise a BadCastException + /// is thrown. + /// Throws InvalidAccessException if Var is empty. + { + VarHolder* pHolder = content(); + + if (pHolder && pHolder->type() == typeid(T)) + { + VarHolderImpl<T>* pHolderImpl = static_cast<VarHolderImpl<T>*>(pHolder); + return pHolderImpl->value(); + } + else if (!pHolder) + throw InvalidAccessException("Can not extract empty value."); + else + throw BadCastException(format("Can not convert %s to %s.", + std::string(pHolder->type().name()), + std::string(typeid(T).name()))); + } + + template <typename T> + Var& operator = (const T& other) + /// Assignment operator for assigning POD to Var + { +#ifdef POCO_NO_SOO + Var tmp(other); + swap(tmp); +#else + construct(other); +#endif + return *this; + } + + bool operator ! () const; + /// Logical NOT operator. + + Var& operator = (const Var& other); + /// Assignment operator specialization for Var + + template <typename T> + const Var operator + (const T& other) const + /// Addition operator for adding POD to Var + { + return convert<T>() + other; + } + + const Var operator + (const Var& other) const; + /// Addition operator specialization for Var + + const Var operator + (const char* other) const; + /// Addition operator specialization for adding const char* to Var + + Var& operator ++ (); + /// Pre-increment operator + + const Var operator ++ (int); + /// Post-increment operator + + Var& operator -- (); + /// Pre-decrement operator + + const Var operator -- (int); + /// Post-decrement operator + + template <typename T> + Var& operator += (const T& other) + /// Addition assignment operator for addition/assignment of POD to Var. + { + return *this = convert<T>() + other; + } + + Var& operator += (const Var& other); + /// Addition assignment operator overload for Var + + Var& operator += (const char* other); + /// Addition assignment operator overload for const char* + + template <typename T> + const Var operator - (const T& other) const + /// Subtraction operator for subtracting POD from Var + { + return convert<T>() - other; + } + + const Var operator - (const Var& other) const; + /// Subtraction operator overload for Var + + template <typename T> + Var& operator -= (const T& other) + /// Subtraction assignment operator + { + return *this = convert<T>() - other; + } + + Var& operator -= (const Var& other); + /// Subtraction assignment operator overload for Var + + template <typename T> + const Var operator * (const T& other) const + /// Multiplication operator for multiplying Var with POD + { + return convert<T>() * other; + } + + const Var operator * (const Var& other) const; + /// Multiplication operator overload for Var + + template <typename T> + Var& operator *= (const T& other) + /// Multiplication assignment operator + { + return *this = convert<T>() * other; + } + + Var& operator *= (const Var& other); + /// Multiplication assignment operator overload for Var + + template <typename T> + const Var operator / (const T& other) const + /// Division operator for dividing Var with POD + { + return convert<T>() / other; + } + + const Var operator / (const Var& other) const; + /// Division operator overload for Var + + template <typename T> + Var& operator /= (const T& other) + /// Division assignment operator + { + return *this = convert<T>() / other; + } + + Var& operator /= (const Var& other); + /// Division assignment operator specialization for Var + + template <typename T> + bool operator == (const T& other) const + /// Equality operator + { + if (isEmpty()) return false; + return convert<T>() == other; + } + + bool operator == (const char* other) const; + /// Equality operator overload for const char* + + bool operator == (const Var& other) const; + /// Equality operator overload for Var + + template <typename T> + bool operator != (const T& other) const + /// Inequality operator + { + if (isEmpty()) return true; + return convert<T>() != other; + } + + bool operator != (const Var& other) const; + /// Inequality operator overload for Var + + bool operator != (const char* other) const; + /// Inequality operator overload for const char* + + template <typename T> + bool operator < (const T& other) const + /// Less than operator + { + if (isEmpty()) return false; + return convert<T>() < other; + } + + bool operator < (const Var& other) const; + /// Less than operator overload for Var + + template <typename T> + bool operator <= (const T& other) const + /// Less than or equal operator + { + if (isEmpty()) return false; + return convert<T>() <= other; + } + + bool operator <= (const Var& other) const; + /// Less than or equal operator overload for Var + + template <typename T> + bool operator > (const T& other) const + /// Greater than operator + { + if (isEmpty()) return false; + return convert<T>() > other; + } + + bool operator > (const Var& other) const; + /// Greater than operator overload for Var + + template <typename T> + bool operator >= (const T& other) const + /// Greater than or equal operator + { + if (isEmpty()) return false; + return convert<T>() >= other; + } + + bool operator >= (const Var& other) const; + /// Greater than or equal operator overload for Var + + template <typename T> + bool operator || (const T& other) const + /// Logical OR operator + { + if (isEmpty()) return false; + return convert<bool>() || other; + } + + bool operator || (const Var& other) const; + /// Logical OR operator operator overload for Var + + template <typename T> + bool operator && (const T& other) const + /// Logical AND operator. + { + if (isEmpty()) return false; + return convert<bool>() && other; + } + + bool operator && (const Var& other) const; + /// Logical AND operator operator overload for Var. + + bool isArray() const; + /// Returns true if Var is an array. + + bool isVector() const; + /// Returns true if Var represents a vector. + + bool isList() const; + /// Returns true if Var represents a list. + + bool isDeque() const; + /// Returns true if Var represents a deque. + + bool isStruct() const; + /// Returns true if Var represents a struct. + + char& at(std::size_t n); + /// Returns character at position n. This function only works with + /// Var containing a std::string. + + + template <typename T> + Var& operator [] (const T& n) + { + return getAt(n); + } + + template <typename T> + const Var& operator [] (const T& n) const + { + return const_cast<Var*>(this)->getAt(n); + } + + Var& operator [] (const std::string& name); + /// Index operator by name, only use on Vars where isStruct + /// returns true! In all other cases InvalidAccessException is thrown. + + const Var& operator [] (const std::string& name) const; + /// Index operator by name, only use on Vars where isStruct + /// returns true! In all other cases InvalidAccessException is thrown. + + const std::type_info& type() const; + /// Returns the type information of the stored content. + + //@ deprecated + void empty(); + /// Empties Var. + /// This function is deprecated and will be removed. + /// Please use clear(). + + void clear(); + /// Empties Var. + + bool isEmpty() const; + /// Returns true if empty. + + bool isInteger() const; + /// Returns true if stored value is integer. + + bool isSigned() const; + /// Returns true if stored value is signed. + + bool isNumeric() const; + /// Returns true if stored value is numeric. + /// Returns false for numeric strings (e.g. "123" is string, not number) + + bool isBoolean() const; + /// Returns true if stored value is boolean. + /// Returns false for boolean strings (e.g. "true" is string, not number) + + bool isString() const; + /// Returns true if stored value is std::string. + + bool isDate() const; + /// Returns true if stored value represents a date. + + bool isTime() const; + /// Returns true if stored value represents time or date/time. + + bool isDateTime() const; + /// Returns true if stored value represents a date/time. + + std::size_t size() const; + /// Returns the size of this Var. + /// This function returns 0 when Var is empty, 1 for POD or the size (i.e. length) + /// for held container. + + std::string toString() const + /// Returns the stored value as string. + { + VarHolder* pHolder = content(); + + if (!pHolder) + throw InvalidAccessException("Can not convert empty value."); + + if (typeid(std::string) == pHolder->type()) + return extract<std::string>(); + else + { + std::string result; + pHolder->convert(result); + return result; + } + } + + static Var parse(const std::string& val); + /// Parses the string which must be in JSON format + + static std::string toString(const Var& var); + /// Converts the Var to a string in JSON format. Note that toString(const Var&) will return + /// a different result than Var::convert<std::string>() and Var::toString()! + +private: + Var& getAt(std::size_t n); + Var& getAt(const std::string& n); + + static Var parse(const std::string& val, std::string::size_type& offset); + /// Parses the string which must be in JSON format + + static Var parseObject(const std::string& val, std::string::size_type& pos); + static Var parseArray(const std::string& val, std::string::size_type& pos); + static std::string parseString(const std::string& val, std::string::size_type& pos); + static std::string parseJSONString(const std::string& val, std::string::size_type& pos); + static void skipWhiteSpace(const std::string& val, std::string::size_type& pos); + + template <typename T> + T add(const Var& other) const + { + return convert<T>() + other.convert<T>(); + } + + template <typename T> + T subtract(const Var& other) const + { + return convert<T>() - other.convert<T>(); + } + + template <typename T> + T multiply(const Var& other) const + { + return convert<T>() * other.convert<T>(); + } + + template <typename T> + T divide(const Var& other) const + { + return convert<T>() / other.convert<T>(); + } + + template <typename T, typename E> + VarHolderImpl<T>* holderImpl(const std::string errorMessage = "") const + { + VarHolder* pHolder = content(); + + if (pHolder && pHolder->type() == typeid(T)) + return static_cast<VarHolderImpl<T>*>(pHolder); + else if (!pHolder) + throw InvalidAccessException("Can not access empty value."); + else + throw E(errorMessage); + } + + Var& structIndexOperator(VarHolderImpl<Struct<int> >* pStr, int n) const; + +#ifdef POCO_NO_SOO + + VarHolder* content() const + { + return _pHolder; + } + + void destruct() + { + if (!isEmpty()) delete content(); + } + + VarHolder* _pHolder; + +#else + + VarHolder* content() const + { + return _placeholder.content(); + } + + template<typename ValueType> + void construct(const ValueType& value) + { + if (sizeof(VarHolderImpl<ValueType>) <= Placeholder<ValueType>::Size::value) + { + new (reinterpret_cast<VarHolder*>(_placeholder.holder)) VarHolderImpl<ValueType>(value); + _placeholder.setLocal(true); + } + else + { + _placeholder.pHolder = new VarHolderImpl<ValueType>(value); + _placeholder.setLocal(false); + } + } + + void construct(const char* value) + { + std::string val(value); + if (sizeof(VarHolderImpl<std::string>) <= Placeholder<std::string>::Size::value) + { + new (reinterpret_cast<VarHolder*>(_placeholder.holder)) VarHolderImpl<std::string>(val); + _placeholder.setLocal(true); + } + else + { + _placeholder.pHolder = new VarHolderImpl<std::string>(val); + _placeholder.setLocal(false); + } + } + + void construct(const Var& other) + { + if (!other.isEmpty()) + other.content()->clone(&_placeholder); + else + _placeholder.erase(); + } + + void destruct() + { + if (!isEmpty()) + { + if (_placeholder.isLocal()) + content()->~VarHolder(); + else + delete content(); + } + } + + Placeholder<VarHolder> _placeholder; + +#endif // POCO_NO_SOO +}; + + +/// +/// inlines +/// + + +/// +/// Var members +/// + +inline void Var::swap(Var& other) +{ +#ifdef POCO_NO_SOO + + std::swap(_pHolder, other._pHolder); + +#else + + if (this == &other) return; + + if (!_placeholder.isLocal() && !other._placeholder.isLocal()) + { + std::swap(_placeholder.pHolder, other._placeholder.pHolder); + } + else + { + Var tmp(*this); + try + { + if (_placeholder.isLocal()) destruct(); + construct(other); + other = tmp; + } + catch (...) + { + construct(tmp); + throw; + } + } + +#endif +} + + +inline const std::type_info& Var::type() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->type() : typeid(void); +} + + +inline Var::ConstIterator Var::begin() const +{ + if (isEmpty()) return ConstIterator(const_cast<Var*>(this), true); + + return ConstIterator(const_cast<Var*>(this), false); +} + +inline Var::ConstIterator Var::end() const +{ + return ConstIterator(const_cast<Var*>(this), true); +} + +inline Var::Iterator Var::begin() +{ + if (isEmpty()) return Iterator(const_cast<Var*>(this), true); + + return Iterator(const_cast<Var*>(this), false); +} + +inline Var::Iterator Var::end() +{ + return Iterator(this, true); +} + + +inline Var& Var::operator [] (const std::string& name) +{ + return getAt(name); +} + + +inline const Var& Var::operator [] (const std::string& name) const +{ + return const_cast<Var*>(this)->getAt(name); +} + + +inline const Var Var::operator + (const char* other) const +{ + return convert<std::string>() + other; +} + + +inline Var& Var::operator += (const char*other) +{ + return *this = convert<std::string>() + other; +} + + +inline bool Var::operator ! () const +{ + return !convert<bool>(); +} + + +inline bool Var::isEmpty() const +{ + return 0 == content(); +} + + +inline bool Var::isArray() const +{ + if (isEmpty() || + isString()) return false; + + VarHolder* pHolder = content(); + return pHolder ? pHolder->isArray() : false; +} + + +inline bool Var::isVector() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isVector() : false; +} + + +inline bool Var::isList() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isList() : false; +} + + +inline bool Var::isDeque() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isDeque() : false; +} + + +inline bool Var::isStruct() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isStruct() : false; +} + + +inline bool Var::isInteger() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isInteger() : false; +} + + +inline bool Var::isSigned() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isSigned() : false; +} + + +inline bool Var::isNumeric() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isNumeric() : false; +} + + +inline bool Var::isBoolean() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isBoolean() : false; +} + + +inline bool Var::isString() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isString() : false; +} + + +inline bool Var::isDate() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isDate() : false; +} + + +inline bool Var::isTime() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isTime() : false; +} + + +inline bool Var::isDateTime() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->isDateTime() : false; +} + + +inline std::size_t Var::size() const +{ + VarHolder* pHolder = content(); + return pHolder ? pHolder->size() : 0; +} + + +/// +/// Var non-member functions +/// + +inline const Var operator + (const char* other, const Var& da) + /// Addition operator for adding Var to const char* +{ + std::string tmp = other; + return tmp + da.convert<std::string>(); +} + + +inline char operator + (const char& other, const Var& da) + /// Addition operator for adding Var to char +{ + return other + da.convert<char>(); +} + + +inline char operator - (const char& other, const Var& da) + /// Subtraction operator for subtracting Var from char +{ + return other - da.convert<char>(); +} + + +inline char operator * (const char& other, const Var& da) + /// Multiplication operator for multiplying Var with char +{ + return other * da.convert<char>(); +} + + +inline char operator / (const char& other, const Var& da) + /// Division operator for dividing Var with char +{ + return other / da.convert<char>(); +} + + +inline char operator += (char& other, const Var& da) + /// Addition assignment operator for adding Var to char +{ + return other += da.convert<char>(); +} + + +inline char operator -= (char& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from char +{ + return other -= da.convert<char>(); +} + + +inline char operator *= (char& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with char +{ + return other *= da.convert<char>(); +} + + +inline char operator /= (char& other, const Var& da) + /// Division assignment operator for dividing Var with char +{ + return other /= da.convert<char>(); +} + + +inline bool operator == (const char& other, const Var& da) + /// Equality operator for comparing Var with char +{ + if (da.isEmpty()) return false; + return other == da.convert<char>(); +} + + +inline bool operator != (const char& other, const Var& da) + /// Inequality operator for comparing Var with char +{ + if (da.isEmpty()) return true; + return other != da.convert<char>(); +} + + +inline bool operator < (const char& other, const Var& da) + /// Less than operator for comparing Var with char +{ + if (da.isEmpty()) return false; + return other < da.convert<char>(); +} + + +inline bool operator <= (const char& other, const Var& da) + /// Less than or equal operator for comparing Var with char +{ + if (da.isEmpty()) return false; + return other <= da.convert<char>(); +} + + +inline bool operator > (const char& other, const Var& da) + /// Greater than operator for comparing Var with char +{ + if (da.isEmpty())return false; + return other > da.convert<char>(); +} + + +inline bool operator >= (const char& other, const Var& da) + /// Greater than or equal operator for comparing Var with char +{ + if (da.isEmpty())return false; + return other >= da.convert<char>(); +} + + +inline Poco::Int8 operator + (const Poco::Int8& other, const Var& da) + /// Addition operator for adding Var to Poco::Int8 +{ + return other + da.convert<Poco::Int8>(); +} + + +inline Poco::Int8 operator - (const Poco::Int8& other, const Var& da) + /// Subtraction operator for subtracting Var from Poco::Int8 +{ + return other - da.convert<Poco::Int8>(); +} + + +inline Poco::Int8 operator * (const Poco::Int8& other, const Var& da) + /// Multiplication operator for multiplying Var with Poco::Int8 +{ + return other * da.convert<Poco::Int8>(); +} + + +inline Poco::Int8 operator / (const Poco::Int8& other, const Var& da) + /// Division operator for dividing Var with Poco::Int8 +{ + return other / da.convert<Poco::Int8>(); +} + + +inline Poco::Int8 operator += (Poco::Int8& other, const Var& da) + /// Addition assignment operator for adding Var to Poco::Int8 +{ + return other += da.convert<Poco::Int8>(); +} + + +inline Poco::Int8 operator -= (Poco::Int8& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from Poco::Int8 +{ + return other -= da.convert<Poco::Int8>(); +} + + +inline Poco::Int8 operator *= (Poco::Int8& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with Poco::Int8 +{ + return other *= da.convert<Poco::Int8>(); +} + + +inline Poco::Int8 operator /= (Poco::Int8& other, const Var& da) + /// Division assignment operator for dividing Var with Poco::Int8 +{ + return other /= da.convert<Poco::Int8>(); +} + + +inline bool operator == (const Poco::Int8& other, const Var& da) + /// Equality operator for comparing Var with Poco::Int8 +{ + if (da.isEmpty()) return false; + return other == da.convert<Poco::Int8>(); +} + + +inline bool operator != (const Poco::Int8& other, const Var& da) + /// Inequality operator for comparing Var with Poco::Int8 +{ + if (da.isEmpty()) return true; + return other != da.convert<Poco::Int8>(); +} + + +inline bool operator < (const Poco::Int8& other, const Var& da) + /// Less than operator for comparing Var with Poco::Int8 +{ + if (da.isEmpty()) return false; + return other < da.convert<Poco::Int8>(); +} + + +inline bool operator <= (const Poco::Int8& other, const Var& da) + /// Less than or equal operator for comparing Var with Poco::Int8 +{ + if (da.isEmpty()) return false; + return other <= da.convert<Poco::Int8>(); +} + + +inline bool operator > (const Poco::Int8& other, const Var& da) + /// Greater than operator for comparing Var with Poco::Int8 +{ + if (da.isEmpty()) return false; + return other > da.convert<Poco::Int8>(); +} + + +inline bool operator >= (const Poco::Int8& other, const Var& da) + /// Greater than or equal operator for comparing Var with Poco::Int8 +{ + if (da.isEmpty()) return false; + return other >= da.convert<Poco::Int8>(); +} + + +inline Poco::UInt8 operator + (const Poco::UInt8& other, const Var& da) + /// Addition operator for adding Var to Poco::UInt8 +{ + return other + da.convert<Poco::UInt8>(); +} + + +inline Poco::UInt8 operator - (const Poco::UInt8& other, const Var& da) + /// Subtraction operator for subtracting Var from Poco::UInt8 +{ + return other - da.convert<Poco::UInt8>(); +} + + +inline Poco::UInt8 operator * (const Poco::UInt8& other, const Var& da) + /// Multiplication operator for multiplying Var with Poco::UInt8 +{ + return other * da.convert<Poco::UInt8>(); +} + + +inline Poco::UInt8 operator / (const Poco::UInt8& other, const Var& da) + /// Division operator for dividing Var with Poco::UInt8 +{ + return other / da.convert<Poco::UInt8>(); +} + + +inline Poco::UInt8 operator += (Poco::UInt8& other, const Var& da) + /// Addition assignment operator for adding Var to Poco::UInt8 +{ + return other += da.convert<Poco::UInt8>(); +} + + +inline Poco::UInt8 operator -= (Poco::UInt8& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from Poco::UInt8 +{ + return other -= da.convert<Poco::UInt8>(); +} + + +inline Poco::UInt8 operator *= (Poco::UInt8& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with Poco::UInt8 +{ + return other *= da.convert<Poco::UInt8>(); +} + + +inline Poco::UInt8 operator /= (Poco::UInt8& other, const Var& da) + /// Division assignment operator for dividing Var with Poco::UInt8 +{ + return other /= da.convert<Poco::UInt8>(); +} + + +inline bool operator == (const Poco::UInt8& other, const Var& da) + /// Equality operator for comparing Var with Poco::UInt8 +{ + if (da.isEmpty()) return false; + return other == da.convert<Poco::UInt8>(); +} + + +inline bool operator != (const Poco::UInt8& other, const Var& da) + /// Inequality operator for comparing Var with Poco::UInt8 +{ + if (da.isEmpty()) return true; + return other != da.convert<Poco::UInt8>(); +} + + +inline bool operator < (const Poco::UInt8& other, const Var& da) + /// Less than operator for comparing Var with Poco::UInt8 +{ + if (da.isEmpty()) return false; + return other < da.convert<Poco::UInt8>(); +} + + +inline bool operator <= (const Poco::UInt8& other, const Var& da) + /// Less than or equal operator for comparing Var with Poco::UInt8 +{ + if (da.isEmpty()) return false; + return other <= da.convert<Poco::UInt8>(); +} + + +inline bool operator > (const Poco::UInt8& other, const Var& da) + /// Greater than operator for comparing Var with Poco::UInt8 +{ + if (da.isEmpty()) return false; + return other > da.convert<Poco::UInt8>(); +} + + +inline bool operator >= (const Poco::UInt8& other, const Var& da) + /// Greater than or equal operator for comparing Var with Poco::UInt8 +{ + if (da.isEmpty()) return false; + return other >= da.convert<Poco::UInt8>(); +} + + +inline Poco::Int16 operator + (const Poco::Int16& other, const Var& da) + /// Addition operator for adding Var to Poco::Int16 +{ + return other + da.convert<Poco::Int16>(); +} + + +inline Poco::Int16 operator - (const Poco::Int16& other, const Var& da) + /// Subtraction operator for subtracting Var from Poco::Int16 +{ + return other - da.convert<Poco::Int16>(); +} + + +inline Poco::Int16 operator * (const Poco::Int16& other, const Var& da) + /// Multiplication operator for multiplying Var with Poco::Int16 +{ + return other * da.convert<Poco::Int16>(); +} + + +inline Poco::Int16 operator / (const Poco::Int16& other, const Var& da) + /// Division operator for dividing Var with Poco::Int16 +{ + return other / da.convert<Poco::Int16>(); +} + + +inline Poco::Int16 operator += (Poco::Int16& other, const Var& da) + /// Addition assignment operator for adding Var to Poco::Int16 +{ + return other += da.convert<Poco::Int16>(); +} + + +inline Poco::Int16 operator -= (Poco::Int16& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from Poco::Int16 +{ + return other -= da.convert<Poco::Int16>(); +} + + +inline Poco::Int16 operator *= (Poco::Int16& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with Poco::Int16 +{ + return other *= da.convert<Poco::Int16>(); +} + + +inline Poco::Int16 operator /= (Poco::Int16& other, const Var& da) + /// Division assignment operator for dividing Var with Poco::Int16 +{ + return other /= da.convert<Poco::Int16>(); +} + + +inline bool operator == (const Poco::Int16& other, const Var& da) + /// Equality operator for comparing Var with Poco::Int16 +{ + if (da.isEmpty()) return false; + return other == da.convert<Poco::Int16>(); +} + + +inline bool operator != (const Poco::Int16& other, const Var& da) + /// Inequality operator for comparing Var with Poco::Int16 +{ + if (da.isEmpty()) return true; + return other != da.convert<Poco::Int16>(); +} + + +inline bool operator < (const Poco::Int16& other, const Var& da) + /// Less than operator for comparing Var with Poco::Int16 +{ + if (da.isEmpty()) return false; + return other < da.convert<Poco::Int16>(); +} + + +inline bool operator <= (const Poco::Int16& other, const Var& da) + /// Less than or equal operator for comparing Var with Poco::Int16 +{ + if (da.isEmpty()) return false; + return other <= da.convert<Poco::Int16>(); +} + + +inline bool operator > (const Poco::Int16& other, const Var& da) + /// Greater than operator for comparing Var with Poco::Int16 +{ + if (da.isEmpty()) return false; + return other > da.convert<Poco::Int16>(); +} + + +inline bool operator >= (const Poco::Int16& other, const Var& da) + /// Greater than or equal operator for comparing Var with Poco::Int16 +{ + if (da.isEmpty()) return false; + return other >= da.convert<Poco::Int16>(); +} + + +inline Poco::UInt16 operator + (const Poco::UInt16& other, const Var& da) + /// Addition operator for adding Var to Poco::UInt16 +{ + return other + da.convert<Poco::UInt16>(); +} + + +inline Poco::UInt16 operator - (const Poco::UInt16& other, const Var& da) + /// Subtraction operator for subtracting Var from Poco::UInt16 +{ + return other - da.convert<Poco::UInt16>(); +} + + +inline Poco::UInt16 operator * (const Poco::UInt16& other, const Var& da) + /// Multiplication operator for multiplying Var with Poco::UInt16 +{ + return other * da.convert<Poco::UInt16>(); +} + + +inline Poco::UInt16 operator / (const Poco::UInt16& other, const Var& da) + /// Division operator for dividing Var with Poco::UInt16 +{ + return other / da.convert<Poco::UInt16>(); +} + + +inline Poco::UInt16 operator += (Poco::UInt16& other, const Var& da) + /// Addition assignment operator for adding Var to Poco::UInt16 +{ + return other += da.convert<Poco::UInt16>(); +} + + +inline Poco::UInt16 operator -= (Poco::UInt16& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from Poco::UInt16 +{ + return other -= da.convert<Poco::UInt16>(); +} + + +inline Poco::UInt16 operator *= (Poco::UInt16& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with Poco::UInt16 +{ + return other *= da.convert<Poco::UInt16>(); +} + + +inline Poco::UInt16 operator /= (Poco::UInt16& other, const Var& da) + /// Division assignment operator for dividing Var with Poco::UInt16 +{ + return other /= da.convert<Poco::UInt16>(); +} + + +inline bool operator == (const Poco::UInt16& other, const Var& da) + /// Equality operator for comparing Var with Poco::UInt16 +{ + if (da.isEmpty()) return false; + return other == da.convert<Poco::UInt16>(); +} + + +inline bool operator != (const Poco::UInt16& other, const Var& da) + /// Inequality operator for comparing Var with Poco::UInt16 +{ + if (da.isEmpty()) return true; + return other != da.convert<Poco::UInt16>(); +} + + +inline bool operator < (const Poco::UInt16& other, const Var& da) + /// Less than operator for comparing Var with Poco::UInt16 +{ + if (da.isEmpty()) return false; + return other < da.convert<Poco::UInt16>(); +} + + +inline bool operator <= (const Poco::UInt16& other, const Var& da) + /// Less than or equal operator for comparing Var with Poco::UInt16 +{ + if (da.isEmpty()) return false; + return other <= da.convert<Poco::UInt16>(); +} + + +inline bool operator > (const Poco::UInt16& other, const Var& da) + /// Greater than operator for comparing Var with Poco::UInt16 +{ + if (da.isEmpty()) return false; + return other > da.convert<Poco::UInt16>(); +} + + +inline bool operator >= (const Poco::UInt16& other, const Var& da) + /// Greater than or equal operator for comparing Var with Poco::UInt16 +{ + if (da.isEmpty()) return false; + return other >= da.convert<Poco::UInt16>(); +} + + +inline Poco::Int32 operator + (const Poco::Int32& other, const Var& da) + /// Addition operator for adding Var to Poco::Int32 +{ + return other + da.convert<Poco::Int32>(); +} + + +inline Poco::Int32 operator - (const Poco::Int32& other, const Var& da) + /// Subtraction operator for subtracting Var from Poco::Int32 +{ + return other - da.convert<Poco::Int32>(); +} + + +inline Poco::Int32 operator * (const Poco::Int32& other, const Var& da) + /// Multiplication operator for multiplying Var with Poco::Int32 +{ + return other * da.convert<Poco::Int32>(); +} + + +inline Poco::Int32 operator / (const Poco::Int32& other, const Var& da) + /// Division operator for dividing Var with Poco::Int32 +{ + return other / da.convert<Poco::Int32>(); +} + + +inline Poco::Int32 operator += (Poco::Int32& other, const Var& da) + /// Addition assignment operator for adding Var to Poco::Int32 +{ + return other += da.convert<Poco::Int32>(); +} + + +inline Poco::Int32 operator -= (Poco::Int32& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from Poco::Int32 +{ + return other -= da.convert<Poco::Int32>(); +} + + +inline Poco::Int32 operator *= (Poco::Int32& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with Poco::Int32 +{ + return other *= da.convert<Poco::Int32>(); +} + + +inline Poco::Int32 operator /= (Poco::Int32& other, const Var& da) + /// Division assignment operator for dividing Var with Poco::Int32 +{ + return other /= da.convert<Poco::Int32>(); +} + + +inline bool operator == (const Poco::Int32& other, const Var& da) + /// Equality operator for comparing Var with Poco::Int32 +{ + if (da.isEmpty()) return false; + return other == da.convert<Poco::Int32>(); +} + + +inline bool operator != (const Poco::Int32& other, const Var& da) + /// Inequality operator for comparing Var with Poco::Int32 +{ + if (da.isEmpty()) return true; + return other != da.convert<Poco::Int32>(); +} + + +inline bool operator < (const Poco::Int32& other, const Var& da) + /// Less than operator for comparing Var with Poco::Int32 +{ + if (da.isEmpty()) return false; + return other < da.convert<Poco::Int32>(); +} + + +inline bool operator <= (const Poco::Int32& other, const Var& da) + /// Less than or equal operator for comparing Var with Poco::Int32 +{ + if (da.isEmpty()) return false; + return other <= da.convert<Poco::Int32>(); +} + + +inline bool operator > (const Poco::Int32& other, const Var& da) + /// Greater than operator for comparing Var with Poco::Int32 +{ + if (da.isEmpty()) return false; + return other > da.convert<Poco::Int32>(); +} + + +inline bool operator >= (const Poco::Int32& other, const Var& da) + /// Greater than or equal operator for comparing Var with Poco::Int32 +{ + if (da.isEmpty()) return false; + return other >= da.convert<Poco::Int32>(); +} + + +inline Poco::UInt32 operator + (const Poco::UInt32& other, const Var& da) + /// Addition operator for adding Var to Poco::UInt32 +{ + return other + da.convert<Poco::UInt32>(); +} + + +inline Poco::UInt32 operator - (const Poco::UInt32& other, const Var& da) + /// Subtraction operator for subtracting Var from Poco::UInt32 +{ + return other - da.convert<Poco::UInt32>(); +} + + +inline Poco::UInt32 operator * (const Poco::UInt32& other, const Var& da) + /// Multiplication operator for multiplying Var with Poco::UInt32 +{ + return other * da.convert<Poco::UInt32>(); +} + + +inline Poco::UInt32 operator / (const Poco::UInt32& other, const Var& da) + /// Division operator for dividing Var with Poco::UInt32 +{ + return other / da.convert<Poco::UInt32>(); +} + + +inline Poco::UInt32 operator += (Poco::UInt32& other, const Var& da) + /// Addition assignment operator for adding Var to Poco::UInt32 +{ + return other += da.convert<Poco::UInt32>(); +} + + +inline Poco::UInt32 operator -= (Poco::UInt32& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from Poco::UInt32 +{ + return other -= da.convert<Poco::UInt32>(); +} + + +inline Poco::UInt32 operator *= (Poco::UInt32& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with Poco::UInt32 +{ + return other *= da.convert<Poco::UInt32>(); +} + + +inline Poco::UInt32 operator /= (Poco::UInt32& other, const Var& da) + /// Division assignment operator for dividing Var with Poco::UInt32 +{ + return other /= da.convert<Poco::UInt32>(); +} + + +inline bool operator == (const Poco::UInt32& other, const Var& da) + /// Equality operator for comparing Var with Poco::UInt32 +{ + if (da.isEmpty()) return false; + return other == da.convert<Poco::UInt32>(); +} + + +inline bool operator != (const Poco::UInt32& other, const Var& da) + /// Inequality operator for comparing Var with Poco::UInt32 +{ + if (da.isEmpty()) return true; + return other != da.convert<Poco::UInt32>(); +} + + +inline bool operator < (const Poco::UInt32& other, const Var& da) + /// Less than operator for comparing Var with Poco::UInt32 +{ + if (da.isEmpty()) return false; + return other < da.convert<Poco::UInt32>(); +} + + +inline bool operator <= (const Poco::UInt32& other, const Var& da) + /// Less than or equal operator for comparing Var with Poco::UInt32 +{ + if (da.isEmpty()) return false; + return other <= da.convert<Poco::UInt32>(); +} + + +inline bool operator > (const Poco::UInt32& other, const Var& da) + /// Greater than operator for comparing Var with Poco::UInt32 +{ + if (da.isEmpty()) return false; + return other > da.convert<Poco::UInt32>(); +} + + +inline bool operator >= (const Poco::UInt32& other, const Var& da) + /// Greater than or equal operator for comparing Var with Poco::UInt32 +{ + if (da.isEmpty()) return false; + return other >= da.convert<Poco::UInt32>(); +} + + +inline Poco::Int64 operator + (const Poco::Int64& other, const Var& da) + /// Addition operator for adding Var to Poco::Int64 +{ + return other + da.convert<Poco::Int64>(); +} + + +inline Poco::Int64 operator - (const Poco::Int64& other, const Var& da) + /// Subtraction operator for subtracting Var from Poco::Int64 +{ + return other - da.convert<Poco::Int64>(); +} + + +inline Poco::Int64 operator * (const Poco::Int64& other, const Var& da) + /// Multiplication operator for multiplying Var with Poco::Int64 +{ + return other * da.convert<Poco::Int64>(); +} + + +inline Poco::Int64 operator / (const Poco::Int64& other, const Var& da) + /// Division operator for dividing Var with Poco::Int64 +{ + return other / da.convert<Poco::Int64>(); +} + + +inline Poco::Int64 operator += (Poco::Int64& other, const Var& da) + /// Addition assignment operator for adding Var to Poco::Int64 +{ + return other += da.convert<Poco::Int64>(); +} + + +inline Poco::Int64 operator -= (Poco::Int64& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from Poco::Int64 +{ + return other -= da.convert<Poco::Int64>(); +} + + +inline Poco::Int64 operator *= (Poco::Int64& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with Poco::Int64 +{ + return other *= da.convert<Poco::Int64>(); +} + + +inline Poco::Int64 operator /= (Poco::Int64& other, const Var& da) + /// Division assignment operator for dividing Var with Poco::Int64 +{ + return other /= da.convert<Poco::Int64>(); +} + + +inline bool operator == (const Poco::Int64& other, const Var& da) + /// Equality operator for comparing Var with Poco::Int64 +{ + if (da.isEmpty()) return false; + return other == da.convert<Poco::Int64>(); +} + + +inline bool operator != (const Poco::Int64& other, const Var& da) + /// Inequality operator for comparing Var with Poco::Int64 +{ + if (da.isEmpty()) return true; + return other != da.convert<Poco::Int64>(); +} + + +inline bool operator < (const Poco::Int64& other, const Var& da) + /// Less than operator for comparing Var with Poco::Int64 +{ + if (da.isEmpty()) return false; + return other < da.convert<Poco::Int64>(); +} + + +inline bool operator <= (const Poco::Int64& other, const Var& da) + /// Less than or equal operator for comparing Var with Poco::Int64 +{ + if (da.isEmpty()) return false; + return other <= da.convert<Poco::Int64>(); +} + + +inline bool operator > (const Poco::Int64& other, const Var& da) + /// Greater than operator for comparing Var with Poco::Int64 +{ + if (da.isEmpty()) return false; + return other > da.convert<Poco::Int64>(); +} + + +inline bool operator >= (const Poco::Int64& other, const Var& da) + /// Greater than or equal operator for comparing Var with Poco::Int64 +{ + if (da.isEmpty()) return false; + return other >= da.convert<Poco::Int64>(); +} + + +inline Poco::UInt64 operator + (const Poco::UInt64& other, const Var& da) + /// Addition operator for adding Var to Poco::UInt64 +{ + return other + da.convert<Poco::UInt64>(); +} + + +inline Poco::UInt64 operator - (const Poco::UInt64& other, const Var& da) + /// Subtraction operator for subtracting Var from Poco::UInt64 +{ + return other - da.convert<Poco::UInt64>(); +} + + +inline Poco::UInt64 operator * (const Poco::UInt64& other, const Var& da) + /// Multiplication operator for multiplying Var with Poco::UInt64 +{ + return other * da.convert<Poco::UInt64>(); +} + + +inline Poco::UInt64 operator / (const Poco::UInt64& other, const Var& da) + /// Division operator for dividing Var with Poco::UInt64 +{ + return other / da.convert<Poco::UInt64>(); +} + + +inline Poco::UInt64 operator += (Poco::UInt64& other, const Var& da) + /// Addition assignment operator for adding Var to Poco::UInt64 +{ + return other += da.convert<Poco::UInt64>(); +} + + +inline Poco::UInt64 operator -= (Poco::UInt64& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from Poco::UInt64 +{ + return other -= da.convert<Poco::UInt64>(); +} + + +inline Poco::UInt64 operator *= (Poco::UInt64& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with Poco::UInt64 +{ + return other *= da.convert<Poco::UInt64>(); +} + + +inline Poco::UInt64 operator /= (Poco::UInt64& other, const Var& da) + /// Division assignment operator for dividing Var with Poco::UInt64 +{ + return other /= da.convert<Poco::UInt64>(); +} + + +inline bool operator == (const Poco::UInt64& other, const Var& da) + /// Equality operator for comparing Var with Poco::UInt64 +{ + if (da.isEmpty()) return false; + return other == da.convert<Poco::UInt64>(); +} + + +inline bool operator != (const Poco::UInt64& other, const Var& da) + /// Inequality operator for comparing Var with Poco::UInt64 +{ + if (da.isEmpty()) return true; + return other != da.convert<Poco::UInt64>(); +} + + +inline bool operator < (const Poco::UInt64& other, const Var& da) + /// Less than operator for comparing Var with Poco::UInt64 +{ + if (da.isEmpty()) return false; + return other < da.convert<Poco::UInt64>(); +} + + +inline bool operator <= (const Poco::UInt64& other, const Var& da) + /// Less than or equal operator for comparing Var with Poco::UInt64 +{ + if (da.isEmpty()) return false; + return other <= da.convert<Poco::UInt64>(); +} + + +inline bool operator > (const Poco::UInt64& other, const Var& da) + /// Greater than operator for comparing Var with Poco::UInt64 +{ + if (da.isEmpty()) return false; + return other > da.convert<Poco::UInt64>(); +} + + +inline bool operator >= (const Poco::UInt64& other, const Var& da) + /// Greater than or equal operator for comparing Var with Poco::UInt64 +{ + if (da.isEmpty()) return false; + return other >= da.convert<Poco::UInt64>(); +} + + +inline float operator + (const float& other, const Var& da) + /// Addition operator for adding Var to float +{ + return other + da.convert<float>(); +} + + +inline float operator - (const float& other, const Var& da) + /// Subtraction operator for subtracting Var from float +{ + return other - da.convert<float>(); +} + + +inline float operator * (const float& other, const Var& da) + /// Multiplication operator for multiplying Var with float +{ + return other * da.convert<float>(); +} + + +inline float operator / (const float& other, const Var& da) + /// Division operator for dividing Var with float +{ + return other / da.convert<float>(); +} + + +inline float operator += (float& other, const Var& da) + /// Addition assignment operator for adding Var to float +{ + return other += da.convert<float>(); +} + + +inline float operator -= (float& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from float +{ + return other -= da.convert<float>(); +} + + +inline float operator *= (float& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with float +{ + return other *= da.convert<float>(); +} + + +inline float operator /= (float& other, const Var& da) + /// Division assignment operator for dividing Var with float +{ + return other /= da.convert<float>(); +} + + +inline bool operator == (const float& other, const Var& da) + /// Equality operator for comparing Var with float +{ + if (da.isEmpty()) return false; + return other == da.convert<float>(); +} + + +inline bool operator != (const float& other, const Var& da) + /// Inequality operator for comparing Var with float +{ + if (da.isEmpty()) return true; + return other != da.convert<float>(); +} + + +inline bool operator < (const float& other, const Var& da) + /// Less than operator for comparing Var with float +{ + if (da.isEmpty()) return false; + return other < da.convert<float>(); +} + + +inline bool operator <= (const float& other, const Var& da) + /// Less than or equal operator for comparing Var with float +{ + if (da.isEmpty()) return false; + return other <= da.convert<float>(); +} + + +inline bool operator > (const float& other, const Var& da) + /// Greater than operator for comparing Var with float +{ + if (da.isEmpty()) return false; + return other > da.convert<float>(); +} + + +inline bool operator >= (const float& other, const Var& da) + /// Greater than or equal operator for comparing Var with float +{ + if (da.isEmpty()) return false; + return other >= da.convert<float>(); +} + + +inline double operator + (const double& other, const Var& da) + /// Addition operator for adding Var to double +{ + return other + da.convert<double>(); +} + + +inline double operator - (const double& other, const Var& da) + /// Subtraction operator for subtracting Var from double +{ + return other - da.convert<double>(); +} + + +inline double operator * (const double& other, const Var& da) + /// Multiplication operator for multiplying Var with double +{ + return other * da.convert<double>(); +} + + +inline double operator / (const double& other, const Var& da) + /// Division operator for dividing Var with double +{ + return other / da.convert<double>(); +} + + +inline double operator += (double& other, const Var& da) + /// Addition assignment operator for adding Var to double +{ + return other += da.convert<double>(); +} + + +inline double operator -= (double& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from double +{ + return other -= da.convert<double>(); +} + + +inline double operator *= (double& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with double +{ + return other *= da.convert<double>(); +} + + +inline double operator /= (double& other, const Var& da) + /// Division assignment operator for dividing Var with double +{ + return other /= da.convert<double>(); +} + + +inline bool operator == (const double& other, const Var& da) + /// Equality operator for comparing Var with double +{ + if (da.isEmpty()) return false; + return other == da.convert<double>(); +} + + +inline bool operator != (const double& other, const Var& da) + /// Inequality operator for comparing Var with double +{ + if (da.isEmpty()) return true; + return other != da.convert<double>(); +} + + +inline bool operator < (const double& other, const Var& da) + /// Less than operator for comparing Var with double +{ + if (da.isEmpty()) return false; + return other < da.convert<double>(); +} + + +inline bool operator <= (const double& other, const Var& da) + /// Less than or equal operator for comparing Var with double +{ + if (da.isEmpty()) return false; + return other <= da.convert<double>(); +} + + +inline bool operator > (const double& other, const Var& da) + /// Greater than operator for comparing Var with double +{ + if (da.isEmpty()) return false; + return other > da.convert<double>(); +} + + +inline bool operator >= (const double& other, const Var& da) + /// Greater than or equal operator for comparing Var with double +{ + if (da.isEmpty()) return false; + return other >= da.convert<double>(); +} + + +inline bool operator == (const bool& other, const Var& da) + /// Equality operator for comparing Var with bool +{ + if (da.isEmpty()) return false; + return other == da.convert<bool>(); +} + + +inline bool operator != (const bool& other, const Var& da) + /// Inequality operator for comparing Var with bool +{ + if (da.isEmpty()) return true; + return other != da.convert<bool>(); +} + + +inline bool operator == (const std::string& other, const Var& da) + /// Equality operator for comparing Var with std::string +{ + if (da.isEmpty()) return false; + return other == da.convert<std::string>(); +} + + +inline bool operator != (const std::string& other, const Var& da) + /// Inequality operator for comparing Var with std::string +{ + if (da.isEmpty()) return true; + return other != da.convert<std::string>(); +} + + +inline bool operator == (const UTF16String& other, const Var& da) + /// Equality operator for comparing Var with UTF16String +{ + if (da.isEmpty()) return false; + return other == da.convert<UTF16String>(); +} + + +inline bool operator != (const UTF16String& other, const Var& da) + /// Inequality operator for comparing Var with UTF16String +{ + if (da.isEmpty()) return true; + return other != da.convert<UTF16String>(); +} + + +inline bool operator == (const char* other, const Var& da) + /// Equality operator for comparing Var with const char* +{ + if (da.isEmpty()) return false; + return da.convert<std::string>() == other; +} + + +inline bool operator != (const char* other, const Var& da) + /// Inequality operator for comparing Var with const char* +{ + if (da.isEmpty()) return true; + return da.convert<std::string>() != other; +} + + +#ifndef POCO_LONG_IS_64_BIT + + +inline long operator + (const long& other, const Var& da) + /// Addition operator for adding Var to long +{ + return other + da.convert<long>(); +} + + +inline long operator - (const long& other, const Var& da) + /// Subtraction operator for subtracting Var from long +{ + return other - da.convert<long>(); +} + + +inline long operator * (const long& other, const Var& da) + /// Multiplication operator for multiplying Var with long +{ + return other * da.convert<long>(); +} + + +inline long operator / (const long& other, const Var& da) + /// Division operator for dividing Var with long +{ + return other / da.convert<long>(); +} + + +inline long operator += (long& other, const Var& da) + /// Addition assignment operator for adding Var to long +{ + return other += da.convert<long>(); +} + + +inline long operator -= (long& other, const Var& da) + /// Subtraction assignment operator for subtracting Var from long +{ + return other -= da.convert<long>(); +} + + +inline long operator *= (long& other, const Var& da) + /// Multiplication assignment operator for multiplying Var with long +{ + return other *= da.convert<long>(); +} + + +inline long operator /= (long& other, const Var& da) + /// Division assignment operator for dividing Var with long +{ + return other /= da.convert<long>(); +} + + +inline bool operator == (const long& other, const Var& da) + /// Equality operator for comparing Var with long +{ + if (da.isEmpty()) return false; + return other == da.convert<long>(); +} + + +inline bool operator != (const long& other, const Var& da) + /// Inequality operator for comparing Var with long +{ + if (da.isEmpty()) return true; + return other != da.convert<long>(); +} + + +inline bool operator < (const long& other, const Var& da) + /// Less than operator for comparing Var with long +{ + if (da.isEmpty()) return false; + return other < da.convert<long>(); +} + + +inline bool operator <= (const long& other, const Var& da) + /// Less than or equal operator for comparing Var with long +{ + if (da.isEmpty()) return false; + return other <= da.convert<long>(); +} + + +inline bool operator > (const long& other, const Var& da) + /// Greater than operator for comparing Var with long +{ + if (da.isEmpty()) return false; + return other > da.convert<long>(); +} + + +inline bool operator >= (const long& other, const Var& da) + /// Greater than or equal operator for comparing Var with long +{ + if (da.isEmpty()) return false; + return other >= da.convert<long>(); +} + + +#endif // POCO_LONG_IS_64_BIT + + +} // namespace Dynamic + + +//@ deprecated +typedef Dynamic::Var DynamicAny; + + +} // namespace Poco + + +#endif // Foundation_Var_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Dynamic/VarHolder.h b/contrib/libs/poco/Foundation/include/Poco/Dynamic/VarHolder.h new file mode 100644 index 0000000000..85af40f449 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Dynamic/VarHolder.h @@ -0,0 +1,4213 @@ +// +// VarHolder.h +// +// Library: Foundation +// Package: Dynamic +// Module: VarHolder +// +// Definition of the VarHolder class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_VarHolder_INCLUDED +#define Foundation_VarHolder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/NumberFormatter.h" +#include "Poco/NumberParser.h" +#include "Poco/DateTime.h" +#include "Poco/Timestamp.h" +#include "Poco/LocalDateTime.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeParser.h" +#include "Poco/String.h" +#include "Poco/UnicodeConverter.h" +#include "Poco/UTFString.h" +#include "Poco/UTF8String.h" +#include "Poco/Any.h" +#include "Poco/Exception.h" +#include <vector> +#include <list> +#include <deque> +#include <typeinfo> +#undef min +#undef max +#include <limits> + + +namespace Poco { +namespace Dynamic { + + +class Var; + + +namespace Impl { + + +bool Foundation_API isJSONString(const Var& any); + /// Returns true for values that should be JSON-formatted as string. + + +void Foundation_API appendJSONKey(std::string& val, const Var& any); + /// Converts the any to a JSON key (i.e. wraps it into double quotes + /// regardless of the underlying type) and appends it to val. + + +void Foundation_API appendJSONString(std::string& val, const Var& any); + /// Converts the any to a JSON string (i.e. wraps it into double quotes) + /// regardless of the underlying type) and appends it to val. + + +void Foundation_API appendJSONValue(std::string& val, const Var& any); + /// Converts the any to a JSON value (if underlying type qualifies + /// as string - see isJSONString() - , it is wrapped into double quotes) + /// and appends it to val + + +template <typename C> +void containerToJSON(C& cont, std::string& val) +{ + // Serialize in JSON format. Note: although this is a vector<T>, the code only + // supports vector<Var>. Total specialization is not possible + // because of the cyclic dependency between Var and VarHolder + + // JSON format definition: [ n times: elem ',' ], no ',' for last elem + val.append("[ "); + typename C::const_iterator it = cont.begin(); + typename C::const_iterator itEnd = cont.end(); + if (!cont.empty()) + { + appendJSONValue(val, *it); + ++it; + } + for (; it != itEnd; ++it) + { + val.append(", "); + appendJSONValue(val, *it); + } + val.append(" ]"); +} + + +} // namespace Impl + + +class Foundation_API VarHolder + /// Interface for a data holder used by the Var class. + /// Provides methods to convert between data types. + /// Only data types for which VarHolder specialization exists are supported. + /// + /// Provided are specializations for all C++ built-in types with addition of + /// std::string, Poco::UTF16String, DateTime, LocalDateTime, Timestamp, std::vector<Var> and DynamicStruct. + /// + /// Additional types can be supported by adding specializations. When implementing specializations, + /// the only condition is that they reside in Poco namespace and implement the pure virtual functions + /// clone() and type(). + /// + /// Those conversions that are not implemented shall fail back to this base + /// class implementation. All the convert() function overloads in this class + /// throw BadCastException. +{ +public: + typedef Var ArrayValueType; + + virtual ~VarHolder(); + /// Destroys the VarHolder. + + virtual VarHolder* clone(Placeholder<VarHolder>* pHolder = 0) const = 0; + /// Implementation must implement this function to + /// deep-copy the VarHolder. + /// If small object optimization is enabled (i.e. if + /// POCO_NO_SOO is not defined), VarHolder will be + /// instantiated in-place if it's size is smaller + /// than POCO_SMALL_OBJECT_SIZE. + + virtual const std::type_info& type() const = 0; + /// Implementation must return the type information + /// (typeid) for the stored content. + + virtual void convert(Int8& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(Int16& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(Int32& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(Int64& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(UInt8& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(UInt16& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(UInt32& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(UInt64& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(DateTime& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(LocalDateTime& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(Timestamp& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + +#ifndef POCO_LONG_IS_64_BIT + + void convert(long& val) const; + /// Calls convert(Int32). + + void convert(unsigned long& val) const; + /// Calls convert(UInt32). + +#else + + virtual void convert(long long& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to suport the conversion. + + virtual void convert(unsigned long long & val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to suport the conversion. + +#endif + + virtual void convert(bool& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(float& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(double& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(char& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(std::string& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual void convert(Poco::UTF16String& val) const; + /// Throws BadCastException. Must be overriden in a type + /// specialization in order to support the conversion. + + virtual bool isArray() const; + /// Returns true. + + virtual bool isVector() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isList() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isDeque() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isStruct() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isInteger() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isSigned() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isNumeric() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isBoolean() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isString() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isDate() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isTime() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual bool isDateTime() const; + /// Returns false. Must be properly overriden in a type + /// specialization in order to support the diagnostic. + + virtual std::size_t size() const; + /// Returns 1 iff Var is not empty or this function overriden. + +protected: + VarHolder(); + /// Creates the VarHolder. + + template <typename T> + VarHolder* cloneHolder(Placeholder<VarHolder>* pVarHolder, const T& val) const + /// Instantiates value holder wrapper. If size of the wrapper is + /// larger than POCO_SMALL_OBJECT_SIZE, holder is instantiated on + /// the heap, otherwise it is instantiated in-place (in the + /// pre-allocated buffer inside the holder). + /// + /// Called from clone() member function of the implementation when + /// small object optimization is enabled. + { +#ifdef POCO_NO_SOO + (void)pVarHolder; + return new VarHolderImpl<T>(val); +#else + poco_check_ptr (pVarHolder); + if ((sizeof(VarHolderImpl<T>) <= Placeholder<T>::Size::value)) + { + new ((VarHolder*) pVarHolder->holder) VarHolderImpl<T>(val); + pVarHolder->setLocal(true); + return (VarHolder*) pVarHolder->holder; + } + else + { + pVarHolder->pHolder = new VarHolderImpl<T>(val); + pVarHolder->setLocal(false); + return pVarHolder->pHolder; + } +#endif + } + + template <typename F, typename T> + void convertToSmaller(const F& from, T& to) const + /// This function is meant to convert signed numeric values from + /// larger to smaller type. It checks the upper and lower bound and + /// if from value is within limits of type T (i.e. check calls do not throw), + /// it is converted. + { + poco_static_assert (std::numeric_limits<F>::is_specialized); + poco_static_assert (std::numeric_limits<T>::is_specialized); + poco_static_assert (std::numeric_limits<F>::is_signed); + poco_static_assert (std::numeric_limits<T>::is_signed); + + if (std::numeric_limits<F>::is_integer) + { + checkUpperLimit<F,T>(from); + checkLowerLimit<F,T>(from); + } + else + { + checkUpperLimitFloat<F,T>(from); + checkLowerLimitFloat<F,T>(from); + } + + to = static_cast<T>(from); + } + + template <typename F, typename T> + void convertToSmallerUnsigned(const F& from, T& to) const + /// This function is meant for converting unsigned integral data types, + /// from larger to smaller type. Since lower limit is always 0 for unsigned types, + /// only the upper limit is checked, thus saving some cycles compared to the signed + /// version of the function. If the value to be converted is smaller than + /// the maximum value for the target type, the conversion is performed. + { + poco_static_assert (std::numeric_limits<F>::is_specialized); + poco_static_assert (std::numeric_limits<T>::is_specialized); + poco_static_assert (!std::numeric_limits<F>::is_signed); + poco_static_assert (!std::numeric_limits<T>::is_signed); + + checkUpperLimit<F,T>(from); + to = static_cast<T>(from); + } + + template <typename F, typename T> + void convertSignedToUnsigned(const F& from, T& to) const + /// This function is meant for converting signed integral data types to + /// unsigned data types. Negative values can not be converted and if one + /// is encountered, RangeException is thrown. + /// If upper limit is within the target data type limits, the conversion is performed. + { + poco_static_assert (std::numeric_limits<F>::is_specialized); + poco_static_assert (std::numeric_limits<T>::is_specialized); + poco_static_assert (std::numeric_limits<F>::is_signed); + poco_static_assert (!std::numeric_limits<T>::is_signed); + + if (from < 0) + throw RangeException("Value too small."); + checkUpperLimit<F,T>(from); + to = static_cast<T>(from); + } + + template <typename F, typename T> + void convertSignedFloatToUnsigned(const F& from, T& to) const + /// This function is meant for converting floating point data types to + /// unsigned integral data types. Negative values can not be converted and if one + /// is encountered, RangeException is thrown. + /// If upper limit is within the target data type limits, the conversion is performed. + { + poco_static_assert (std::numeric_limits<F>::is_specialized); + poco_static_assert (std::numeric_limits<T>::is_specialized); + poco_static_assert (!std::numeric_limits<F>::is_integer); + poco_static_assert (std::numeric_limits<T>::is_integer); + poco_static_assert (!std::numeric_limits<T>::is_signed); + + if (from < 0) + throw RangeException("Value too small."); + checkUpperLimitFloat<F,T>(from); + to = static_cast<T>(from); + } + + template <typename F, typename T> + void convertUnsignedToSigned(const F& from, T& to) const + /// This function is meant for converting unsigned integral data types to + /// signed integral data types. Negative values can not be converted and if one + /// is encountered, RangeException is thrown. + /// If upper limit is within the target data type limits, the conversion is performed. + { + poco_static_assert (std::numeric_limits<F>::is_specialized); + poco_static_assert (std::numeric_limits<T>::is_specialized); + poco_static_assert (!std::numeric_limits<F>::is_signed); + poco_static_assert (std::numeric_limits<T>::is_signed); + + checkUpperLimit<F,T>(from); + to = static_cast<T>(from); + } + +private: + +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable : 4127 ) +#pragma warning( disable : 4018 ) +#endif + + template <typename F, typename T> + void checkUpperLimit(const F& from) const + { + // casting to type of smaller size AND + // 'from' is greater than 'T' max value + if ((sizeof(T) < sizeof(F)) && + (from > static_cast<F>(std::numeric_limits<T>::max()))) + { + throw RangeException("Value too large."); + } + // casting to type of equal/bigger size AND + // 'F' is signed AND + // 'T' is unsigned AND + // 'from' is negative + else if (std::numeric_limits<F>::is_signed && + !std::numeric_limits<T>::is_signed && from < 0) + { + throw RangeException("Value too small."); + } + // casting to type of equal/bigger size AND + // 'F' is unsigned AND + // 'T' is signed AND + // 'from' is greater than 'T' max value + else if (!std::numeric_limits<F>::is_signed && + std::numeric_limits<T>::is_signed && + static_cast<Poco::UInt64>(from) > std::numeric_limits<T>::max()) + { + throw RangeException("Value too large."); + } + } + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + template <typename F, typename T> + void checkUpperLimitFloat(const F& from) const + { + if (from > std::numeric_limits<T>::max()) + throw RangeException("Value too large."); + } + + template <typename F, typename T> + void checkLowerLimitFloat(const F& from) const + { + if (from < -std::numeric_limits<T>::max()) + throw RangeException("Value too small."); + } + + template <typename F, typename T> + void checkLowerLimit(const F& from) const + { + if (from < std::numeric_limits<T>::min()) + throw RangeException("Value too small."); + } +}; + + +// +// inlines +// + + +inline void VarHolder::convert(Int8& /*val*/) const +{ + throw BadCastException("Can not convert to Int8"); +} + + +inline void VarHolder::convert(Int16& /*val*/) const +{ + throw BadCastException("Can not convert to Int16"); +} + + +inline void VarHolder::convert(Int32& /*val*/) const +{ + throw BadCastException("Can not convert to Int32"); +} + + +inline void VarHolder::convert(Int64& /*val*/) const +{ + throw BadCastException("Can not convert to Int64"); +} + + +inline void VarHolder::convert(UInt8& /*val*/) const +{ + throw BadCastException("Can not convert to UInt8"); +} + + +inline void VarHolder::convert(UInt16& /*val*/) const +{ + throw BadCastException("Can not convert to UInt16"); +} + + +inline void VarHolder::convert(UInt32& /*val*/) const +{ + throw BadCastException("Can not convert to UInt32"); +} + + +inline void VarHolder::convert(UInt64& /*val*/) const +{ + throw BadCastException("Can not convert to UInt64"); +} + + +inline void VarHolder::convert(DateTime& /*val*/) const +{ + throw BadCastException("Can not convert to DateTime"); +} + + +inline void VarHolder::convert(LocalDateTime& /*val*/) const +{ + throw BadCastException("Can not convert to LocalDateTime"); +} + + +inline void VarHolder::convert(Timestamp& /*val*/) const +{ + throw BadCastException("Can not convert to Timestamp"); +} + +#ifndef POCO_LONG_IS_64_BIT + +inline void VarHolder::convert(long& val) const +{ + Int32 tmp; + convert(tmp); + val = tmp; +} + + +inline void VarHolder::convert(unsigned long& val) const +{ + UInt32 tmp; + convert(tmp); + val = tmp; +} + +#else + +inline void VarHolder::convert(long long& /*val*/) const +{ + throw BadCastException("Can not convert to long long"); +} + + +inline void VarHolder::convert(unsigned long long& /*val*/) const +{ + throw BadCastException("Can not convert to unsigned long long"); +} + +#endif + +inline void VarHolder::convert(bool& /*val*/) const +{ + throw BadCastException("Can not convert to bool"); +} + + +inline void VarHolder::convert(float& /*val*/) const +{ + throw BadCastException("Can not convert to float"); +} + + +inline void VarHolder::convert(double& /*val*/) const +{ + throw BadCastException("Can not convert to double"); +} + + +inline void VarHolder::convert(char& /*val*/) const +{ + throw BadCastException("Can not convert to char"); +} + + +inline void VarHolder::convert(std::string& /*val*/) const +{ + throw BadCastException("Can not convert to std::string"); +} + + +inline void VarHolder::convert(Poco::UTF16String& /*val*/) const +{ + throw BadCastException("Can not convert to Poco::UTF16String"); +} + + +inline bool VarHolder::isArray() const +{ + return true; +} + + +inline bool VarHolder::isVector() const +{ + return false; +} + + +inline bool VarHolder::isList() const +{ + return false; +} + + +inline bool VarHolder::isDeque() const +{ + return false; +} + + +inline bool VarHolder::isStruct() const +{ + return false; +} + +inline bool VarHolder::isInteger() const +{ + return false; +} + + +inline bool VarHolder::isSigned() const +{ + return false; +} + + +inline bool VarHolder::isNumeric() const +{ + return false; +} + + +inline bool VarHolder::isBoolean() const +{ + return false; +} + + +inline bool VarHolder::isString() const +{ + return false; +} + + +inline bool VarHolder::isDate() const +{ + return false; +} + + +inline bool VarHolder::isTime() const +{ + return false; +} + + +inline bool VarHolder::isDateTime() const +{ + return false; +} + +inline std::size_t VarHolder::size() const +{ + return 1u; +} + + +template <typename T> +class VarHolderImpl: public VarHolder + /// Template based implementation of a VarHolder. + /// This class provides type storage for user-defined types + /// that do not have VarHolderImpl specialization. + /// + /// The actual conversion work happens in the template specializations + /// of this class. + /// + /// VarHolderImpl throws following exceptions: + /// BadCastException (if the requested conversion is not implemented) + /// RangeException (if an attempt is made to assign a numeric value outside of the target min/max limits + /// SyntaxException (if an attempt is made to convert a string containing non-numeric characters to number) + /// + /// In order to support efficient direct extraction of the held value, + /// all specializations must additionally implement a public member function: + /// + /// const T& value() const + /// + /// returning a const reference to the actual stored value. +{ +public: + VarHolderImpl(const T& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(T); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const T& value() const + { + return _val; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + T _val; +}; + + +template <> +class VarHolderImpl<Int8>: public VarHolder +{ +public: + VarHolderImpl(Int8 val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Int8); + } + + void convert(Int8& val) const + { + val = _val; + } + + void convert(Int16& val) const + { + val = _val; + } + + void convert(Int32& val) const + { + val = _val; + } + + void convert(Int64& val) const + { + val = _val; + } + + void convert(UInt8& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + convertSignedToUnsigned(_val, val); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = _val; + } + + void convert(unsigned long long& val) const + { + convertSignedToUnsigned(_val, val); + } + +#endif + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + val = static_cast<char>(_val); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + void convert(Poco::UTF16String& val) const + { + std::string str = NumberFormatter::format(_val); + Poco::UnicodeConverter::convert(str, val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Int8& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<Int8>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<Int8>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<Int8>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + Int8 _val; +}; + + +template <> +class VarHolderImpl<Int16>: public VarHolder +{ +public: + VarHolderImpl(Int16 val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Int16); + } + + void convert(Int8& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int16& val) const + { + val = _val; + } + + void convert(Int32& val) const + { + val = _val; + } + + void convert(Int64& val) const + { + val = _val; + } + + void convert(UInt8& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + convertSignedToUnsigned(_val, val); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = _val; + } + + void convert(unsigned long long& val) const + { + convertSignedToUnsigned(_val, val); + } + +#endif + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + void convert(Poco::UTF16String& val) const + { + std::string str = NumberFormatter::format(_val); + Poco::UnicodeConverter::convert(str, val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Int16& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<Int16>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<Int16>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<Int16>::is_specialized; + } + + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + Int16 _val; +}; + + +template <> +class VarHolderImpl<Int32>: public VarHolder +{ +public: + VarHolderImpl(Int32 val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Int32); + } + + void convert(Int8& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int16& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int32& val) const + { + val = _val; + } + + void convert(Int64& val) const + { + val = _val; + } + + void convert(UInt8& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + convertSignedToUnsigned(_val, val); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = _val; + } + + void convert(unsigned long long& val) const + { + convertSignedToUnsigned(_val, val); + } + +#endif + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Int32& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<Int32>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<Int32>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<Int32>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + Int32 _val; +}; + + +template <> +class VarHolderImpl<Int64>: public VarHolder +{ +public: + VarHolderImpl(Int64 val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Int64); + } + + void convert(Int8& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int16& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int32& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int64& val) const + { + val = _val; + } + + void convert(UInt8& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + convertSignedToUnsigned(_val, val); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = _val; + } + + void convert(unsigned long long& val) const + { + convertSignedToUnsigned(_val, val); + } + +#endif + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + void convert(DateTime& dt) const + { + dt = Timestamp(_val); + } + + void convert(LocalDateTime& ldt) const + { + ldt = Timestamp(_val); + } + + void convert(Timestamp& val) const + { + val = Timestamp(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Int64& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<Int64>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<Int64>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<Int64>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + Int64 _val; +}; + + +template <> +class VarHolderImpl<UInt8>: public VarHolder +{ +public: + VarHolderImpl(UInt8 val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(UInt8); + } + + void convert(Int8& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int16& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int32& val) const + { + val = static_cast<Int32>(_val); + } + + void convert(Int64& val) const + { + val = static_cast<Int64>(_val); + } + + void convert(UInt8& val) const + { + val = _val; + } + + void convert(UInt16& val) const + { + val = _val; + } + + void convert(UInt32& val) const + { + val = _val; + } + + void convert(UInt64& val) const + { + val = _val; + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = static_cast<long long>(_val); + } + + void convert(unsigned long long& val) const + { + val = _val; + } + +#endif + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const UInt8& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<UInt8>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<UInt8>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<UInt8>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + UInt8 _val; +}; + + +template <> +class VarHolderImpl<UInt16>: public VarHolder +{ +public: + VarHolderImpl(UInt16 val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(UInt16); + } + + void convert(Int8& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int16& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int32& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int64& val) const + { + val = static_cast<Int64>(_val); + } + + void convert(UInt8& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + val = _val; + } + + void convert(UInt32& val) const + { + val = _val; + } + + void convert(UInt64& val) const + { + val = _val; + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = static_cast<long long>(_val); + } + + void convert(unsigned long long& val) const + { + val = _val; + } + +#endif + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const UInt16& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<UInt16>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<UInt16>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<UInt16>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + UInt16 _val; +}; + + +template <> +class VarHolderImpl<UInt32>: public VarHolder +{ +public: + VarHolderImpl(UInt32 val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(UInt32); + } + + void convert(Int8& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int16& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int32& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int64& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(UInt8& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + val = _val; + } + + void convert(UInt64& val) const + { + val = _val; + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(unsigned long long& val) const + { + val = _val; + } + +#endif + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const UInt32& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<UInt32>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<UInt32>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<UInt32>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + UInt32 _val; +}; + + +template <> +class VarHolderImpl<UInt64>: public VarHolder +{ +public: + VarHolderImpl(UInt64 val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(UInt64); + } + + void convert(Int8& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int16& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int32& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int64& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(UInt8& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + val = _val; + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(unsigned long long& val) const + { + val = _val; + } + +#endif + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + void convert(DateTime& dt) const + { + Int64 val; + convertUnsignedToSigned(_val, val); + dt = Timestamp(val); + } + + void convert(LocalDateTime& ldt) const + { + Int64 val; + convertUnsignedToSigned(_val, val); + ldt = Timestamp(val); + } + + void convert(Timestamp& val) const + { + Int64 tmp; + convertUnsignedToSigned(_val, tmp); + val = Timestamp(tmp); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const UInt64& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<UInt64>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<UInt64>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<UInt64>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + UInt64 _val; +}; + + +template <> +class VarHolderImpl<bool>: public VarHolder +{ +public: + VarHolderImpl(bool val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(bool); + } + + void convert(Int8& val) const + { + val = static_cast<Int8>(_val ? 1 : 0); + } + + void convert(Int16& val) const + { + val = static_cast<Int16>(_val ? 1 : 0); + } + + void convert(Int32& val) const + { + val = static_cast<Int32>(_val ? 1 : 0); + } + + void convert(Int64& val) const + { + val = static_cast<Int64>(_val ? 1 : 0); + } + + void convert(UInt8& val) const + { + val = static_cast<UInt8>(_val ? 1 : 0); + } + + void convert(UInt16& val) const + { + val = static_cast<UInt16>(_val ? 1 : 0); + } + + void convert(UInt32& val) const + { + val = static_cast<UInt32>(_val ? 1 : 0); + } + + void convert(UInt64& val) const + { + val = static_cast<UInt64>(_val ? 1 : 0); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = static_cast<long long>(_val ? 1 : 0); + } + + void convert(unsigned long long& val) const + { + val = static_cast<unsigned long long>(_val ? 1 : 0); + } + +#endif + + void convert(bool& val) const + { + val = _val; + } + + void convert(float& val) const + { + val = (_val ? 1.0f : 0.0f); + } + + void convert(double& val) const + { + val = (_val ? 1.0 : 0.0); + } + + void convert(char& val) const + { + val = static_cast<char>(_val ? 1 : 0); + } + + void convert(std::string& val) const + { + val = (_val ? "true" : "false"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const bool& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<bool>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<bool>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<bool>::is_specialized; + } + + bool isBoolean() const + { + return true; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + bool _val; +}; + + +template <> +class VarHolderImpl<float>: public VarHolder +{ +public: + VarHolderImpl(float val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(float); + } + + void convert(Int8& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int16& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int32& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int64& val) const + { + convertToSmaller(_val, val); + } + + void convert(UInt8& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + convertToSmaller(_val, val); + } + + void convert(unsigned long long& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + +#endif + + void convert(bool& val) const + { + val = !(_val <= std::numeric_limits<float>::min() && + _val >= -1 * std::numeric_limits<float>::min()); + } + + void convert(float& val) const + { + val = _val; + } + + void convert(double& val) const + { + val = _val; + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const float& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<float>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<float>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<float>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + float _val; +}; + + +template <> +class VarHolderImpl<double>: public VarHolder +{ +public: + VarHolderImpl(double val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(double); + } + + void convert(Int8& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int16& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int32& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int64& val) const + { + convertToSmaller(_val, val); + } + + void convert(UInt8& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + convertToSmaller(_val, val); + } + + void convert(unsigned long long& val) const + { + convertSignedFloatToUnsigned(_val, val); + } + +#endif + + void convert(bool& val) const + { + val = !(_val <= std::numeric_limits<double>::min() && + _val >= -1 * std::numeric_limits<double>::min()); + } + + void convert(float& val) const + { + double fMin = -1 * std::numeric_limits<float>::max(); + double fMax = std::numeric_limits<float>::max(); + + if (_val < fMin) throw RangeException("Value too small."); + if (_val > fMax) throw RangeException("Value too large."); + + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = _val; + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const double& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<double>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<double>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<double>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + double _val; +}; + + +template <> +class VarHolderImpl<char>: public VarHolder +{ +public: + VarHolderImpl(char val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(char); + } + + void convert(Int8& val) const + { + val = static_cast<Int8>(_val); + } + + void convert(Int16& val) const + { + val = static_cast<UInt8>(_val); + } + + void convert(Int32& val) const + { + val = static_cast<UInt8>(_val); + } + + void convert(Int64& val) const + { + val = static_cast<UInt8>(_val); + } + + void convert(UInt8& val) const + { + val = static_cast<UInt8>(_val); + } + + void convert(UInt16& val) const + { + val = static_cast<UInt8>(_val); + } + + void convert(UInt32& val) const + { + val = static_cast<UInt8>(_val); + } + + void convert(UInt64& val) const + { + val = static_cast<UInt8>(_val); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = static_cast<long long>(_val); + } + + void convert(unsigned long long& val) const + { + val = static_cast<unsigned long long>(_val); + } + +#endif + + void convert(bool& val) const + { + val = (_val != '\0'); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + val = _val; + } + + void convert(std::string& val) const + { + val = std::string(1, _val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const char& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<char>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<char>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<char>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + char _val; +}; + + +template <> +class VarHolderImpl<std::string>: public VarHolder +{ +public: + VarHolderImpl(const char* pVal): _val(pVal) + { + } + + VarHolderImpl(const std::string& val) : _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(std::string); + } + + void convert(Int8& val) const + { + int v = NumberParser::parse(_val); + convertToSmaller(v, val); + } + + void convert(Int16& val) const + { + int v = NumberParser::parse(_val); + convertToSmaller(v, val); + } + + void convert(Int32& val) const + { + val = NumberParser::parse(_val); + } + + void convert(Int64& val) const + { + val = NumberParser::parse64(_val); + } + + void convert(UInt8& val) const + { + unsigned int v = NumberParser::parseUnsigned(_val); + convertToSmallerUnsigned(v, val); + } + + void convert(UInt16& val) const + { + unsigned int v = NumberParser::parseUnsigned(_val); + convertToSmallerUnsigned(v, val); + } + + void convert(UInt32& val) const + { + val = NumberParser::parseUnsigned(_val); + } + + void convert(UInt64& val) const + { + val = NumberParser::parseUnsigned64(_val); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = NumberParser::parse64(_val); + } + + void convert(unsigned long long& val) const + { + val = NumberParser::parseUnsigned64(_val); + } + +#endif + + void convert(bool& val) const + { + if (_val.empty()) + { + val = false; + return; + } + + static const std::string VAL_FALSE("false"); + static const std::string VAL_INT_FALSE("0"); + val = (_val != VAL_INT_FALSE && + (icompare(_val, VAL_FALSE) != 0)); + } + + void convert(float& val) const + { + double v = NumberParser::parseFloat(_val); + convertToSmaller(v, val); + } + + void convert(double& val) const + { + val = NumberParser::parseFloat(_val); + } + + void convert(char& val) const + { + if (_val.empty()) + val = '\0'; + else + val = _val[0]; + } + + void convert(std::string& val) const + { + val = _val; + } + + void convert(Poco::UTF16String& val) const + { + Poco::UnicodeConverter::convert(_val, val); + } + + void convert(DateTime& val) const + { + int tzd = 0; + if (!DateTimeParser::tryParse(DateTimeFormat::ISO8601_FORMAT, _val, val, tzd)) + throw BadCastException("string -> DateTime"); + } + + void convert(LocalDateTime& ldt) const + { + int tzd = 0; + DateTime tmp; + if (!DateTimeParser::tryParse(DateTimeFormat::ISO8601_FORMAT, _val, tmp, tzd)) + throw BadCastException("string -> LocalDateTime"); + + ldt = LocalDateTime(tzd, tmp, false); + } + + void convert(Timestamp& ts) const + { + int tzd = 0; + DateTime tmp; + if (!DateTimeParser::tryParse(DateTimeFormat::ISO8601_FORMAT, _val, tmp, tzd)) + throw BadCastException("string -> Timestamp"); + + ts = tmp.timestamp(); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const std:: string& value() const + { + return _val; + } + + bool isString() const + { + return true; + } + + std::size_t size() const + { + return _val.length(); + } + + char& operator[](std::string::size_type n) + { + if (n < size()) return _val.operator[](n); + + throw RangeException("String index out of range"); + } + + const char& operator[](std::string::size_type n) const + { + if (n < size()) return _val.operator[](n); + + throw RangeException("String index out of range"); + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + std::string _val; +}; + + +template <> +class VarHolderImpl<UTF16String>: public VarHolder +{ +public: + VarHolderImpl(const char* pVal) : _val(Poco::UnicodeConverter::to<UTF16String>(pVal)) + { + } + + VarHolderImpl(const Poco::UTF16String& val) : _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Poco::UTF16String); + } + + void convert(Int8& val) const + { + int v = NumberParser::parse(toStdString()); + convertToSmaller(v, val); + } + + void convert(Int16& val) const + { + int v = NumberParser::parse(toStdString()); + convertToSmaller(v, val); + } + + void convert(Int32& val) const + { + val = NumberParser::parse(toStdString()); + } + + void convert(Int64& val) const + { + val = NumberParser::parse64(toStdString()); + } + + void convert(UInt8& val) const + { + unsigned int v = NumberParser::parseUnsigned(toStdString()); + convertToSmallerUnsigned(v, val); + } + + void convert(UInt16& val) const + { + unsigned int v = NumberParser::parseUnsigned(toStdString()); + convertToSmallerUnsigned(v, val); + } + + void convert(UInt32& val) const + { + val = NumberParser::parseUnsigned(toStdString()); + } + + void convert(UInt64& val) const + { + val = NumberParser::parseUnsigned64(toStdString()); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = NumberParser::parse64(toStdString()); + } + + void convert(unsigned long long& val) const + { + val = NumberParser::parseUnsigned64(toStdString()); + } + +#endif + + void convert(bool& val) const + { + static const std::string VAL_FALSE("false"); + static const std::string VAL_INT_FALSE("0"); + + if (_val.empty()) val = false; + + std::string str; + UnicodeConverter::convert(_val, str); + val = (str != VAL_INT_FALSE && + (icompare(str, VAL_FALSE) != 0)); + } + + void convert(float& val) const + { + double v = NumberParser::parseFloat(toStdString()); + convertToSmaller(v, val); + } + + void convert(double& val) const + { + val = NumberParser::parseFloat(toStdString()); + } + + void convert(char& val) const + { + if (_val.empty()) + val = '\0'; + else + { + std::string s; + UnicodeConverter::convert(_val, s); + val = s[0]; + } + } + + void convert(Poco::UTF16String& val) const + { + val = _val; + } + + void convert(std::string& val) const + { + UnicodeConverter::convert(_val, val); + } + + void convert(DateTime& val) const + { + int tzd = 0; + if (!DateTimeParser::tryParse(DateTimeFormat::ISO8601_FORMAT, toStdString(), val, tzd)) + throw BadCastException("string -> DateTime"); + } + + void convert(LocalDateTime& ldt) const + { + int tzd = 0; + DateTime tmp; + if (!DateTimeParser::tryParse(DateTimeFormat::ISO8601_FORMAT, toStdString(), tmp, tzd)) + throw BadCastException("string -> LocalDateTime"); + + ldt = LocalDateTime(tzd, tmp, false); + } + + void convert(Timestamp& ts) const + { + int tzd = 0; + DateTime tmp; + if (!DateTimeParser::tryParse(DateTimeFormat::ISO8601_FORMAT, toStdString(), tmp, tzd)) + throw BadCastException("string -> Timestamp"); + + ts = tmp.timestamp(); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Poco::UTF16String& value() const + { + return _val; + } + + bool isString() const + { + return true; + } + + std::size_t size() const + { + return _val.length(); + } + + UTF16Char& operator[](Poco::UTF16String::size_type n) + { + if (n < size()) return _val.operator[](n); + + throw RangeException("String index out of range"); + } + + const UTF16Char& operator[](Poco::UTF16String::size_type n) const + { + if (n < size()) return _val.operator[](n); + + throw RangeException("String index out of range"); + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + std::string toStdString() const + { + std::string str; + UnicodeConverter::convert(_val, str); + return str; + } + + Poco::UTF16String _val; +}; + + +#ifndef POCO_LONG_IS_64_BIT + + +template <> +class VarHolderImpl<long>: public VarHolder +{ +public: + VarHolderImpl(long val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(long); + } + + void convert(Int8& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int16& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int32& val) const + { + val = static_cast<Int32>(_val); + } + + void convert(Int64& val) const + { + val = static_cast<Int64>(_val); + } + + void convert(UInt8& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const long& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<long>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<long>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<long>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + long _val; +}; + + +template <> +class VarHolderImpl<unsigned long>: public VarHolder +{ +public: + VarHolderImpl(unsigned long val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(unsigned long); + } + + void convert(Int8& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int16& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int32& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int64& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(UInt8& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + val = static_cast<UInt64>(_val); + } + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const unsigned long& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<unsigned long>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<unsigned long>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<unsigned long>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + unsigned long _val; +}; + + +#else // if defined (POCO_LONG_IS_64_BIT) + + +template <> +class VarHolderImpl<long long>: public VarHolder +{ +public: + VarHolderImpl(long long val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(long long); + } + + void convert(Int8& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int16& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int32& val) const + { + convertToSmaller(_val, val); + } + + void convert(Int64& val) const + { + val = static_cast<Int64>(_val); + } + + void convert(UInt8& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(long long& val) const + { + val = _val; + } + + void convert(unsigned long long& val) const + { + convertSignedToUnsigned(_val, val); + } + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const long long& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<long long>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<long long>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<long long>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + long long _val; +}; + + +template <> +class VarHolderImpl<unsigned long long>: public VarHolder +{ +public: + VarHolderImpl(unsigned long long val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(unsigned long long); + } + + void convert(Int8& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int16& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int32& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(Int64& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(UInt8& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt16& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt32& val) const + { + convertToSmallerUnsigned(_val, val); + } + + void convert(UInt64& val) const + { + val = static_cast<UInt64>(_val); + } + + void convert(long long& val) const + { + convertUnsignedToSigned(_val, val); + } + + void convert(unsigned long long& val) const + { + val = _val; + } + + void convert(bool& val) const + { + val = (_val != 0); + } + + void convert(float& val) const + { + val = static_cast<float>(_val); + } + + void convert(double& val) const + { + val = static_cast<double>(_val); + } + + void convert(char& val) const + { + UInt8 tmp; + convert(tmp); + val = static_cast<char>(tmp); + } + + void convert(std::string& val) const + { + val = NumberFormatter::format(_val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const unsigned long long& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return std::numeric_limits<unsigned long long>::is_integer; + } + + bool isSigned() const + { + return std::numeric_limits<unsigned long long>::is_signed; + } + + bool isNumeric() const + { + return std::numeric_limits<unsigned long long>::is_specialized; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + unsigned long long _val; +}; + + +#endif // 64bit + + +template <typename T> +class VarHolderImpl<std::vector<T> >: public VarHolder +{ +public: + VarHolderImpl(const std::vector<T>& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(std::vector<T>); + } + + void convert(std::string& val) const + { + Impl::containerToJSON(_val, val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const std::vector<T>& value() const + { + return _val; + } + + bool isVector() const + { + return true; + } + + std::size_t size() const + { + return _val.size(); + } + + T& operator[](typename std::vector<T>::size_type n) + { + if (n < size()) return _val.operator[](n); + + throw RangeException("List index out of range"); + } + + const T& operator[](typename std::vector<T>::size_type n) const + { + if (n < size()) return _val.operator[](n); + + throw RangeException("List index out of range"); + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + std::vector<T> _val; +}; + + +template <typename T> +class VarHolderImpl<std::list<T> >: public VarHolder +{ +public: + VarHolderImpl(const std::list<T>& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(std::list<T>); + } + + void convert(std::string& val) const + { + Impl::containerToJSON(_val, val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const std::list<T>& value() const + { + return _val; + } + + bool isList() const + { + return true; + } + + std::size_t size() const + { + return _val.size(); + } + + T& operator[](typename std::list<T>::size_type n) + { + if (n >= size()) + throw RangeException("List index out of range"); + + typename std::list<T>::size_type counter = 0; + typename std::list<T>::iterator it = _val.begin(); + for (; counter < n; ++counter) ++it; + + return *it; + } + + const T& operator[](typename std::list<T>::size_type n) const + { + if (n >= size()) + throw RangeException("List index out of range"); + + typename std::list<T>::size_type counter = 0; + typename std::list<T>::const_iterator it = _val.begin(); + for (; counter < n; ++counter) ++it; + + return *it; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + std::list<T> _val; +}; + + +template <typename T> +class VarHolderImpl<std::deque<T> >: public VarHolder +{ +public: + VarHolderImpl(const std::deque<T>& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(std::deque<T>); + } + + void convert(std::string& val) const + { + Impl::containerToJSON(_val, val); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const std::deque<T>& value() const + { + return _val; + } + + bool isDeque() const + { + return true; + } + + std::size_t size() const + { + return _val.size(); + } + + T& operator[](typename std::deque<T>::size_type n) + { + if (n < size()) return _val.operator[](n); + + throw RangeException("List index out of range"); + } + + const T& operator[](typename std::deque<T>::size_type n) const + { + if (n < size()) return _val.operator[](n); + + throw RangeException("List index out of range"); + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + std::deque<T> _val; +}; + + +template <> +class VarHolderImpl<DateTime>: public VarHolder +{ +public: + VarHolderImpl(const DateTime& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(DateTime); + } + + void convert(Int8& /*val*/) const + { + throw BadCastException(); + } + + void convert(Int16& /*val*/) const + { + throw BadCastException(); + } + + void convert(Int32& /*val*/) const + { + throw BadCastException(); + } + + void convert(Int64& val) const + { + val = _val.timestamp().epochMicroseconds(); + } + + void convert(UInt64& val) const + { + val = _val.timestamp().epochMicroseconds(); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = _val.timestamp().epochMicroseconds(); + } + + void convert(unsigned long long& val) const + { + val = _val.timestamp().epochMicroseconds(); + } + +#endif + + void convert(std::string& val) const + { + val = DateTimeFormatter::format(_val, Poco::DateTimeFormat::ISO8601_FORMAT); + } + + void convert(DateTime& val) const + { + val = _val; + } + + void convert(LocalDateTime& ldt) const + { + ldt = _val.timestamp(); + } + + void convert(Timestamp& ts) const + { + ts = _val.timestamp(); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const DateTime& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + + bool isDate() const + { + return true; + } + + bool isTime() const + { + return true; + } + + bool isDateTime() const + { + return true; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + DateTime _val; +}; + + +template <> +class VarHolderImpl<LocalDateTime>: public VarHolder +{ +public: + VarHolderImpl(const LocalDateTime& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(LocalDateTime); + } + + void convert(Int64& val) const + { + val = _val.timestamp().epochMicroseconds(); + } + + void convert(UInt64& val) const + { + val = _val.timestamp().epochMicroseconds(); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = _val.timestamp().epochMicroseconds(); + } + + void convert(unsigned long long& val) const + { + val = _val.timestamp().epochMicroseconds(); + } + +#endif + + void convert(std::string& val) const + { + val = DateTimeFormatter::format(_val, Poco::DateTimeFormat::ISO8601_FORMAT); + } + + void convert(DateTime& val) const + { + val = _val.timestamp(); + } + + void convert(LocalDateTime& ldt) const + { + ldt = _val; + } + + void convert(Timestamp& ts) const + { + ts = _val.timestamp(); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const LocalDateTime& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + + bool isDate() const + { + return true; + } + + bool isTime() const + { + return true; + } + + bool isDateTime() const + { + return true; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + LocalDateTime _val; +}; + + +template <> +class VarHolderImpl<Timestamp>: public VarHolder +{ +public: + VarHolderImpl(const Timestamp& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(Timestamp); + } + + void convert(Int64& val) const + { + val = _val.epochMicroseconds(); + } + + void convert(UInt64& val) const + { + val = _val.epochMicroseconds(); + } + +#ifdef POCO_LONG_IS_64_BIT + + void convert(long long& val) const + { + val = _val.epochMicroseconds(); + } + + void convert(unsigned long long& val) const + { + val = _val.epochMicroseconds(); + } + +#endif + + void convert(std::string& val) const + { + val = DateTimeFormatter::format(_val, Poco::DateTimeFormat::ISO8601_FORMAT); + } + + void convert(DateTime& val) const + { + val = _val; + } + + void convert(LocalDateTime& ldt) const + { + ldt = _val; + } + + void convert(Timestamp& ts) const + { + ts = _val; + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const Timestamp& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isStruct() const + { + return false; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isBoolean() const + { + return false; + } + + bool isString() const + { + return false; + } + + bool isDate() const + { + return true; + } + + bool isTime() const + { + return true; + } + + bool isDateTime() const + { + return true; + } + +private: + VarHolderImpl(); + VarHolderImpl(const VarHolderImpl&); + VarHolderImpl& operator = (const VarHolderImpl&); + + Timestamp _val; +}; + + +typedef std::vector<Var> Vector; +typedef std::deque<Var> Deque; +typedef std::list<Var> List; +typedef Vector Array; + + +} } // namespace Poco::Dynamic + + +#endif // Foundation_VarHolder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Dynamic/VarIterator.h b/contrib/libs/poco/Foundation/include/Poco/Dynamic/VarIterator.h new file mode 100644 index 0000000000..a91bb3a6a2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Dynamic/VarIterator.h @@ -0,0 +1,150 @@ +// +// VarIterator.h +// +// Library: Foundation +// Package: Dynamic +// Module: VarIterator +// +// Definition of the VarIterator class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_VarIterator_INCLUDED +#define Foundation_VarIterator_INCLUDED + + +#include "Poco/Exception.h" +#include <iterator> +#include <algorithm> + + +namespace Poco { +namespace Dynamic { + + +class Var; + + +class Foundation_API VarIterator + /// VarIterator class. +{ +public: + typedef std::bidirectional_iterator_tag iterator_category; + typedef Var value_type; + typedef std::ptrdiff_t difference_type; + typedef Var* pointer; + typedef Var& reference; + + static const std::size_t POSITION_END; + /// End position indicator. + + VarIterator(Var* pVar, bool positionEnd); + /// Creates the VarIterator and positions it at the end of + /// the recordset if positionEnd is true. Otherwise, it is + /// positioned at the beginning. + + VarIterator(const VarIterator& other); + /// Creates a copy of other VarIterator. + + ~VarIterator(); + /// Destroys the VarIterator. + + VarIterator& operator = (const VarIterator& other); + /// Assigns the other VarIterator. + + bool operator == (const VarIterator& other) const; + /// Equality operator. + + bool operator != (const VarIterator& other) const; + /// Inequality operator. + + Var& operator * () const; + /// Returns value at the current position. + + Var* operator -> () const; + /// Returns pointer to the value at current position. + + const VarIterator& operator ++ () const; + /// Advances by one position and returns current position. + + VarIterator operator ++ (int) const; + /// Advances by one position and returns copy of the iterator with + /// previous current position. + + const VarIterator& operator -- () const; + /// Goes back by one position and returns copy of the iterator with + /// previous current position. + + VarIterator operator -- (int) const; + /// Goes back by one position and returns previous current position. + + VarIterator operator + (std::size_t diff) const; + /// Returns a copy the VarIterator advanced by diff positions. + + VarIterator operator - (std::size_t diff) const; + /// Returns a copy the VarIterator backed by diff positions. + /// Throws RangeException if diff is larger than current position. + + void swap(VarIterator& other); + /// Swaps the VarIterator with another one. + +private: + VarIterator(); + + void increment() const; + /// Increments the iterator position by one. + /// Throws RangeException if position is out of range. + + void decrement() const; + /// Decrements the iterator position by one. + /// Throws RangeException if position is out of range. + + void setPosition(std::size_t pos) const; + /// Sets the iterator position. + /// Throws RangeException if position is out of range. + + Var* _pVar; + mutable std::size_t _position; + + friend class Var; +}; + + +/// +/// inlines +/// + + +inline bool VarIterator::operator == (const VarIterator& other) const +{ + return _pVar == other._pVar && _position == other._position; +} + + +inline bool VarIterator::operator != (const VarIterator& other) const +{ + return _pVar != other._pVar || _position != other._position; +} + + +} } // namespace Poco::Dynamic + + +namespace std +{ + template<> + inline void swap<Poco::Dynamic::VarIterator>(Poco::Dynamic::VarIterator& s1, + Poco::Dynamic::VarIterator& s2) + /// Full template specialization of std:::swap for VarIterator + { + s1.swap(s2); + } +} + + +#endif // Foundation_VarIterator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DynamicAny.h b/contrib/libs/poco/Foundation/include/Poco/DynamicAny.h new file mode 100644 index 0000000000..214a296792 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DynamicAny.h @@ -0,0 +1,24 @@ +// +// DynamicAny.h +// +// Library: Foundation +// Package: Dynamic +// Module: Var +// +// Forward header for Var class to maintain backward compatibility. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DynamicAny_INCLUDED +#define Foundation_DynamicAny_INCLUDED + +//@ deprecated +#include "Poco/Dynamic/Var.h" + + +#endif // Foundation_DynamicAny_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DynamicAnyHolder.h b/contrib/libs/poco/Foundation/include/Poco/DynamicAnyHolder.h new file mode 100644 index 0000000000..4400af3ec9 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DynamicAnyHolder.h @@ -0,0 +1,24 @@ +// +// DynamicAnyHolder.h +// +// Library: Foundation +// Package: Dynamic +// Module: VarHolder +// +// Forward header for VarHolder class to maintain backward compatibility +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DynamicAnyHolder_INCLUDED +#define Foundation_DynamicAnyHolder_INCLUDED + +//@ deprecated +#include "Poco/Dynamic/VarHolder.h" + + +#endif // Foundation_DynamicAnyHolder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DynamicFactory.h b/contrib/libs/poco/Foundation/include/Poco/DynamicFactory.h new file mode 100644 index 0000000000..5f94204930 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DynamicFactory.h @@ -0,0 +1,141 @@ +// +// DynamicFactory.h +// +// Library: Foundation +// Package: Core +// Module: DynamicFactory +// +// Definition of the DynamicFactory class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DynamicFactory_INCLUDED +#define Foundation_DynamicFactory_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Instantiator.h" +#include "Poco/Exception.h" +#include "Poco/Mutex.h" +#include <map> +#include <memory> + + +namespace Poco { + + +template <class Base> +class DynamicFactory + /// A factory that creates objects by class name. +{ +public: + typedef AbstractInstantiator<Base> AbstractFactory; + + DynamicFactory() + /// Creates the DynamicFactory. + { + } + + ~DynamicFactory() + /// Destroys the DynamicFactory and deletes the instantiators for + /// all registered classes. + { + for (typename FactoryMap::iterator it = _map.begin(); it != _map.end(); ++it) + { + delete it->second; + } + } + + Base* createInstance(const std::string& className) const + /// Creates a new instance of the class with the given name. + /// The class must have been registered with registerClass. + /// If the class name is unknown, a NotFoundException is thrown. + { + FastMutex::ScopedLock lock(_mutex); + + typename FactoryMap::const_iterator it = _map.find(className); + if (it != _map.end()) + return it->second->createInstance(); + else + throw NotFoundException(className); + } + + template <class C> + void registerClass(const std::string& className) + /// Registers the instantiator for the given class with the DynamicFactory. + /// The DynamicFactory takes ownership of the instantiator and deletes + /// it when it's no longer used. + /// If the class has already been registered, an ExistsException is thrown + /// and the instantiator is deleted. + { + registerClass(className, new Instantiator<C, Base>); + } + + void registerClass(const std::string& className, AbstractFactory* pAbstractFactory) + /// Registers the instantiator for the given class with the DynamicFactory. + /// The DynamicFactory takes ownership of the instantiator and deletes + /// it when it's no longer used. + /// If the class has already been registered, an ExistsException is thrown + /// and the instantiator is deleted. + { + poco_check_ptr (pAbstractFactory); + + FastMutex::ScopedLock lock(_mutex); + +#ifndef POCO_ENABLE_CPP11 + std::auto_ptr<AbstractFactory> ptr(pAbstractFactory); +#else + std::unique_ptr<AbstractFactory> ptr(pAbstractFactory); +#endif // POCO_ENABLE_CPP11 + + typename FactoryMap::iterator it = _map.find(className); + if (it == _map.end()) + _map[className] = ptr.release(); + else + throw ExistsException(className); + } + + void unregisterClass(const std::string& className) + /// Unregisters the given class and deletes the instantiator + /// for the class. + /// Throws a NotFoundException if the class has not been registered. + { + FastMutex::ScopedLock lock(_mutex); + + typename FactoryMap::iterator it = _map.find(className); + if (it != _map.end()) + { + delete it->second; + _map.erase(it); + } + else throw NotFoundException(className); + } + + bool isClass(const std::string& className) const + /// Returns true iff the given class has been registered. + { + FastMutex::ScopedLock lock(_mutex); + + return _map.find(className) != _map.end(); + } + +private: + DynamicFactory(const DynamicFactory&); + DynamicFactory& operator = (const DynamicFactory&); + + typedef std::map<std::string, AbstractFactory*> FactoryMap; + + FactoryMap _map; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_DynamicFactory_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/DynamicStruct.h b/contrib/libs/poco/Foundation/include/Poco/DynamicStruct.h new file mode 100644 index 0000000000..1f0fb56b75 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/DynamicStruct.h @@ -0,0 +1,24 @@ +// +// DynamicStruct.h +// +// Library: Foundation +// Package: Dynamic +// Module: Struct +// +// Forward header for Struct class to maintain backward compatibility. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_DynamicStruct_INCLUDED +#define Foundation_DynamicStruct_INCLUDED + +//@ deprecated +#include "Poco/Dynamic/Struct.h" + + +#endif // Foundation_DynamicStruct_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Environment.h b/contrib/libs/poco/Foundation/include/Poco/Environment.h new file mode 100644 index 0000000000..a422109129 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Environment.h @@ -0,0 +1,123 @@ +// +// Environment.h +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the Environment class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Environment_INCLUDED +#define Foundation_Environment_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Environment + /// This class provides access to environment variables + /// and some general system information. +{ +public: + typedef UInt8 NodeId[6]; /// Ethernet address. + + static std::string get(const std::string& name); + /// Returns the value of the environment variable + /// with the given name. Throws a NotFoundException + /// if the variable does not exist. + + static std::string get(const std::string& name, const std::string& defaultValue); + /// Returns the value of the environment variable + /// with the given name. If the environment variable + /// is undefined, returns defaultValue instead. + + static bool has(const std::string& name); + /// Returns true iff an environment variable + /// with the given name is defined. + + static void set(const std::string& name, const std::string& value); + /// Sets the environment variable with the given name + /// to the given value. + + static std::string osName(); + /// Returns the operating system name. + + static std::string osDisplayName(); + /// Returns the operating system name in a + /// "user-friendly" way. + /// + /// Currently this is only implemented for + /// Windows. There it will return names like + /// "Windows XP" or "Windows 7/Server 2008 SP2". + /// On other platforms, returns the same as + /// osName(). + + static std::string osVersion(); + /// Returns the operating system version. + + static std::string osArchitecture(); + /// Returns the operating system architecture. + + static std::string nodeName(); + /// Returns the node (or host) name. + + static void nodeId(NodeId& id); + /// Returns the Ethernet address of the first Ethernet + /// adapter found on the system. + /// + /// Throws a SystemException if no Ethernet adapter is available. + + static std::string nodeId(); + /// Returns the Ethernet address (format "xx:xx:xx:xx:xx:xx") + /// of the first Ethernet adapter found on the system. + /// + /// Throws a SystemException if no Ethernet adapter is available. + + static unsigned processorCount(); + /// Returns the number of processors installed in the system. + /// + /// If the number of processors cannot be determined, returns 1. + + static Poco::UInt32 libraryVersion(); + /// Returns the POCO C++ Libraries version as a hexadecimal + /// number in format 0xAABBCCDD, where + /// - AA is the major version number, + /// - BB is the minor version number, + /// - CC is the revision number, and + /// - DD is the patch level number. + /// + /// Some patch level ranges have special meanings: + /// - Dx mark development releases, + /// - Ax mark alpha releases, and + /// - Bx mark beta releases. + + static Poco::Int32 os(); + /// Return the operating system as defined + /// in the include Foundation/Platform.h (POCO_OS) + + static Poco::Int32 arch(); + /// Return the underlying cpu architecture that runs this operating system + /// as defined in Foundation/Platform (POCO_ARCH) + + static bool isUnix(); + /// Return true if the operating system belongs to the Linux family + + static bool isWindows(); + /// Return true if the operating system belongs to the Windows family +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Environment_UNIX.h b/contrib/libs/poco/Foundation/include/Poco/Environment_UNIX.h new file mode 100644 index 0000000000..d6ae543ff9 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Environment_UNIX.h @@ -0,0 +1,56 @@ +// +// Environment_UNIX.h +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Environment_UNIX_INCLUDED +#define Foundation_Environment_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include <map> + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + typedef UInt8 NodeId[6]; /// Ethernet address. + + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osDisplayNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); + static void nodeIdImpl(NodeId& id); + static unsigned processorCountImpl(); + +private: + typedef std::map<std::string, std::string> StringMap; + + static StringMap _map; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Environment_VX.h b/contrib/libs/poco/Foundation/include/Poco/Environment_VX.h new file mode 100644 index 0000000000..8eb178d03b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Environment_VX.h @@ -0,0 +1,56 @@ +// +// Environment_VX.h +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for VxWorks. +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Environment_VX_INCLUDED +#define Foundation_Environment_VX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include <map> + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + typedef UInt8 NodeId[6]; /// Ethernet address. + + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osDisplayNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); + static void nodeIdImpl(NodeId& id); + static unsigned processorCountImpl(); + +private: + typedef std::map<std::string, std::string> StringMap; + + static StringMap _map; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Environment_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/Environment_WIN32.h new file mode 100644 index 0000000000..bfac7c590b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Environment_WIN32.h @@ -0,0 +1,48 @@ +// +// Environment_WIN32.h +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Environment_WIN32_INCLUDED +#define Foundation_Environment_WIN32_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + typedef UInt8 NodeId[6]; /// Ethernet address. + + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osDisplayNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); + static void nodeIdImpl(NodeId& id); + static unsigned processorCountImpl(); +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Environment_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/Environment_WIN32U.h new file mode 100644 index 0000000000..b54afb2e89 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Environment_WIN32U.h @@ -0,0 +1,48 @@ +// +// Environment_WIN32U.h +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for WIN32. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Environment_WIN32U_INCLUDED +#define Foundation_Environment_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + typedef UInt8 NodeId[6]; /// Ethernet address. + + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osDisplayNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); + static void nodeIdImpl(NodeId& id); + static unsigned processorCountImpl(); +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Environment_WINCE.h b/contrib/libs/poco/Foundation/include/Poco/Environment_WINCE.h new file mode 100644 index 0000000000..0c92bc540c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Environment_WINCE.h @@ -0,0 +1,59 @@ +// +// Environment_WINCE.h +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for WINCE. +// +// Copyright (c) 2009-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Environment_WINCE_INCLUDED +#define Foundation_Environment_WINCE_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + typedef UInt8 NodeId[6]; /// Ethernet address. + + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osDisplayNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); + static void nodeIdImpl(NodeId& id); + static unsigned processorCountImpl(); + +private: + static bool envVar(const std::string& name, std::string* value); + + static const std::string TEMP; + static const std::string TMP; + static const std::string HOMEPATH; + static const std::string COMPUTERNAME; + static const std::string OS; + static const std::string NUMBER_OF_PROCESSORS; + static const std::string PROCESSOR_ARCHITECTURE; +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_WINCE_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Error.h b/contrib/libs/poco/Foundation/include/Poco/Error.h new file mode 100644 index 0000000000..935ee22343 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Error.h @@ -0,0 +1,52 @@ +// +// Error.h +// +// Library: Foundation +// Package: Core +// Module: Error +// +// Definition of the Error class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Error_INCLUDED +#define Foundation_Error_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Error + /// The Error class provides utility functions + /// for error reporting. +{ +public: + +#ifdef POCO_OS_FAMILY_WINDOWS + static DWORD last(); + /// Utility function returning the last error. + + static std::string getMessage(DWORD errorCode); + /// Utility function translating numeric error code to string. +#else + static int last(); + /// Utility function returning the last error. + + static std::string getMessage(int errorCode); + /// Utility function translating numeric error code to string. +#endif +}; + + +} // namespace Poco + + +#endif // Foundation_Error_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ErrorHandler.h b/contrib/libs/poco/Foundation/include/Poco/ErrorHandler.h new file mode 100644 index 0000000000..a3eea3b143 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ErrorHandler.h @@ -0,0 +1,120 @@ +// +// ErrorHandler.h +// +// Library: Foundation +// Package: Threading +// Module: ErrorHandler +// +// Definition of the ErrorHandler class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ErrorHandler_INCLUDED +#define Foundation_ErrorHandler_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API ErrorHandler + /// This is the base class for thread error handlers. + /// + /// An unhandled exception that causes a thread to terminate is usually + /// silently ignored, since the class library cannot do anything meaningful + /// about it. + /// + /// The Thread class provides the possibility to register a + /// global ErrorHandler that is invoked whenever a thread has + /// been terminated by an unhandled exception. + /// The ErrorHandler must be derived from this class and can + /// provide implementations of all three exception() overloads. + /// + /// The ErrorHandler is always invoked within the context of + /// the offending thread. +{ +public: + ErrorHandler(); + /// Creates the ErrorHandler. + + virtual ~ErrorHandler(); + /// Destroys the ErrorHandler. + + virtual void exception(const Exception& exc); + /// Called when a Poco::Exception (or a subclass) + /// caused the thread to terminate. + /// + /// This method should not throw any exception - it would + /// be silently ignored. + /// + /// The default implementation just breaks into the debugger. + + virtual void exception(const std::exception& exc); + /// Called when a std::exception (or a subclass) + /// caused the thread to terminate. + /// + /// This method should not throw any exception - it would + /// be silently ignored. + /// + /// The default implementation just breaks into the debugger. + + virtual void exception(); + /// Called when an exception that is neither a + /// Poco::Exception nor a std::exception caused + /// the thread to terminate. + /// + /// This method should not throw any exception - it would + /// be silently ignored. + /// + /// The default implementation just breaks into the debugger. + + static void handle(const Exception& exc); + /// Invokes the currently registered ErrorHandler. + + static void handle(const std::exception& exc); + /// Invokes the currently registered ErrorHandler. + + static void handle(); + /// Invokes the currently registered ErrorHandler. + + static ErrorHandler* set(ErrorHandler* pHandler); + /// Registers the given handler as the current error handler. + /// + /// Returns the previously registered handler. + + static ErrorHandler* get(); + /// Returns a pointer to the currently registered + /// ErrorHandler. + +protected: + static ErrorHandler* defaultHandler(); + /// Returns the default ErrorHandler. + +private: + static ErrorHandler* _pHandler; + static FastMutex _mutex; +}; + + +// +// inlines +// +inline ErrorHandler* ErrorHandler::get() +{ + return _pHandler; +} + + +} // namespace Poco + + +#endif // Foundation_ErrorHandler_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Event.h b/contrib/libs/poco/Foundation/include/Poco/Event.h new file mode 100644 index 0000000000..c6e20b65aa --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Event.h @@ -0,0 +1,123 @@ +// +// Event.h +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Definition of the Event class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Event_INCLUDED +#define Foundation_Event_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/Event_WIN32.h" +#elif defined(POCO_VXWORKS) +#include "Poco/Event_VX.h" +#else +#include "Poco/Event_POSIX.h" +#endif + + +namespace Poco { + + +class Foundation_API Event: private EventImpl + /// An Event is a synchronization object that + /// allows one thread to signal one or more + /// other threads that a certain event + /// has happened. + /// Usually, one thread signals an event, + /// while one or more other threads wait + /// for an event to become signalled. +{ +public: + Event(bool autoReset = true); + /// Creates the event. If autoReset is true, + /// the event is automatically reset after + /// a wait() successfully returns. + + ~Event(); + /// Destroys the event. + + void set(); + /// Signals the event. If autoReset is true, + /// only one thread waiting for the event + /// can resume execution. + /// If autoReset is false, all waiting threads + /// can resume execution. + + void wait(); + /// Waits for the event to become signalled. + + void wait(long milliseconds); + /// Waits for the event to become signalled. + /// Throws a TimeoutException if the event + /// does not become signalled within the specified + /// time interval. + + bool tryWait(long milliseconds); + /// Waits for the event to become signalled. + /// Returns true if the event + /// became signalled within the specified + /// time interval, false otherwise. + + void reset(); + /// Resets the event to unsignalled state. + +private: + Event(const Event&); + Event& operator = (const Event&); +}; + + +// +// inlines +// +inline void Event::set() +{ + setImpl(); +} + + +inline void Event::wait() +{ + waitImpl(); +} + + +inline void Event::wait(long milliseconds) +{ + if (!waitImpl(milliseconds)) + throw TimeoutException(); +} + + +inline bool Event::tryWait(long milliseconds) +{ + return waitImpl(milliseconds); +} + + +inline void Event::reset() +{ + resetImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_Event_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/EventArgs.h b/contrib/libs/poco/Foundation/include/Poco/EventArgs.h new file mode 100644 index 0000000000..0066790706 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/EventArgs.h @@ -0,0 +1,45 @@ +// +// EventArgs.h +// +// Library: Foundation +// Package: Events +// Module: EventArgs +// +// Definition of EventArgs. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_EventArgs_INCLUDED +#define Foundation_EventArgs_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API EventArgs + /// The purpose of the EventArgs class is to be used as parameter + /// when one doesn't want to send any data. + /// + /// One can use EventArgs as a base class for one's own event arguments + /// but with the arguments being a template parameter this is not + /// necessary. +{ +public: + EventArgs(); + + virtual ~EventArgs(); +}; + + +} // namespace Poco + + +#endif diff --git a/contrib/libs/poco/Foundation/include/Poco/EventChannel.h b/contrib/libs/poco/Foundation/include/Poco/EventChannel.h new file mode 100644 index 0000000000..07975167dd --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/EventChannel.h @@ -0,0 +1,54 @@ +// +// EventChannel.h +// +// Library: Foundation +// Package: Logging +// Module: EventChannel +// +// Definition of the EventChannel class. +// +// Copyright (c) 2015, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_EventChannel_INCLUDED +#define Foundation_EventChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Message.h" +#include "Poco/BasicEvent.h" + + +namespace Poco { + + +class Foundation_API EventChannel: public Channel + /// The EventChannel fires the messageLogged event for every log message + /// received. This can be used to hook custom log message processing into + /// the logging framework. +{ +public: + Poco::BasicEvent<const Message> messageLogged; + /// Fired when a message is logged by calling the log() method. + + EventChannel(); + /// Creates the EventChannel. + + void log(const Message& msg); + /// Fires the messageLogged event. + +protected: + ~EventChannel(); + /// Destroys the EventChannel. +}; + + +} // namespace Poco + + +#endif // Foundation_EventChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/EventLogChannel.h b/contrib/libs/poco/Foundation/include/Poco/EventLogChannel.h new file mode 100644 index 0000000000..bcaf3a42e5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/EventLogChannel.h @@ -0,0 +1,105 @@ +// +// EventLogChannel.h +// +// Library: Foundation +// Package: Logging +// Module: EventLogChannel +// +// Definition of the EventLogChannel class specific to WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_EventLogChannel_INCLUDED +#define Foundation_EventLogChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API EventLogChannel: public Channel + /// This Windows-only channel works with the Windows NT Event Log + /// service. + /// + /// To work properly, the EventLogChannel class requires that either + /// the PocoFoundation.dll or the PocoMsg.dll Dynamic Link Library + /// containing the message definition resources can be found in $PATH. +{ +public: + EventLogChannel(); + /// Creates the EventLogChannel. + /// The name of the current application (or more correctly, + /// the name of its executable) is taken as event source name. + + EventLogChannel(const std::string& name); + /// Creates the EventLogChannel with the given event source name. + + EventLogChannel(const std::string& name, const std::string& host); + /// Creates an EventLogChannel with the given event source + /// name that routes messages to the given host. + + void open(); + /// Opens the EventLogChannel. If necessary, the + /// required registry entries to register a + /// message resource DLL are made. + + void close(); + /// Closes the EventLogChannel. + + void log(const Message& msg); + /// Logs the given message to the Windows Event Log. + /// + /// The message type and priority are mapped to + /// appropriate values for Event Log type and category. + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// The following properties are supported: + /// + /// * name: The name of the event source. + /// * loghost: The name of the host where the Event Log service is running. + /// The default is "localhost". + /// * host: same as host. + /// * logfile: The name of the log file. The default is "Application". + + std::string getProperty(const std::string& name) const; + /// Returns the value of the given property. + + static const std::string PROP_NAME; + static const std::string PROP_HOST; + static const std::string PROP_LOGHOST; + static const std::string PROP_LOGFILE; + +protected: + ~EventLogChannel(); + static int getType(const Message& msg); + static int getCategory(const Message& msg); + void setUpRegistry() const; +#if defined(POCO_WIN32_UTF8) + static std::wstring findLibrary(const wchar_t* name); +#else + static std::string findLibrary(const char* name); +#endif + +private: + std::string _name; + std::string _host; + std::string _logFile; + HANDLE _h; +}; + + +} // namespace Poco + + +#endif // Foundation_EventLogChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Event_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/Event_POSIX.h new file mode 100644 index 0000000000..b7eb83aa6e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Event_POSIX.h @@ -0,0 +1,77 @@ +// +// Event_POSIX.h +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Definition of the EventImpl class for POSIX Threads. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Event_POSIX_INCLUDED +#define Foundation_Event_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <pthread.h> +#include <errno.h> + + +namespace Poco { + + +class Foundation_API EventImpl +{ +protected: + EventImpl(bool autoReset); + ~EventImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + void resetImpl(); + +private: + bool _auto; + volatile bool _state; + pthread_mutex_t _mutex; + pthread_cond_t _cond; +}; + + +// +// inlines +// +inline void EventImpl::setImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot signal event (lock)"); + _state = true; + if (pthread_cond_broadcast(&_cond)) + { + pthread_mutex_unlock(&_mutex); + throw SystemException("cannot signal event"); + } + pthread_mutex_unlock(&_mutex); +} + + +inline void EventImpl::resetImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot reset event"); + _state = false; + pthread_mutex_unlock(&_mutex); +} + + +} // namespace Poco + + +#endif // Foundation_Event_POSIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Event_VX.h b/contrib/libs/poco/Foundation/include/Poco/Event_VX.h new file mode 100644 index 0000000000..9dd23c75e4 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Event_VX.h @@ -0,0 +1,49 @@ +// +// Event_VX.h +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Definition of the EventImpl class for VxWorks. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Event_VX_INCLUDED +#define Foundation_Event_VX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <semLib.h> + + +namespace Poco { + + +class Foundation_API EventImpl +{ +protected: + EventImpl(bool autoReset); + ~EventImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + void resetImpl(); + +private: + bool _auto; + volatile bool _state; + SEM_ID _sem; +}; + + +} // namespace Poco + + +#endif // Foundation_Event_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Event_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/Event_WIN32.h new file mode 100644 index 0000000000..07fdb09847 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Event_WIN32.h @@ -0,0 +1,68 @@ +// +// Event_WIN32.h +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Definition of the EventImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Event_WIN32_INCLUDED +#define Foundation_Event_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API EventImpl +{ +protected: + EventImpl(bool autoReset); + ~EventImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + void resetImpl(); + +private: + HANDLE _event; +}; + + +// +// inlines +// +inline void EventImpl::setImpl() +{ + if (!SetEvent(_event)) + { + throw SystemException("cannot signal event"); + } +} + + +inline void EventImpl::resetImpl() +{ + if (!ResetEvent(_event)) + { + throw SystemException("cannot reset event"); + } +} + + +} // namespace Poco + + +#endif // Foundation_Event_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Exception.h b/contrib/libs/poco/Foundation/include/Poco/Exception.h new file mode 100644 index 0000000000..b2ad47ce89 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Exception.h @@ -0,0 +1,261 @@ +// +// Exception.h +// +// Library: Foundation +// Package: Core +// Module: Exception +// +// Definition of various Poco exception classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Exception_INCLUDED +#define Foundation_Exception_INCLUDED + + +#include "Poco/Foundation.h" +#include <stdexcept> + + +namespace Poco { + + +class Foundation_API Exception: public std::exception + /// This is the base class for all exceptions defined + /// in the Poco class library. +{ +public: + Exception(const std::string& msg, int code = 0); + /// Creates an exception. + + Exception(const std::string& msg, const std::string& arg, int code = 0); + /// Creates an exception. + + Exception(const std::string& msg, const Exception& nested, int code = 0); + /// Creates an exception and stores a clone + /// of the nested exception. + + Exception(const Exception& exc); + /// Copy constructor. + + ~Exception() noexcept; + /// Destroys the exception and deletes the nested exception. + + Exception& operator = (const Exception& exc); + /// Assignment operator. + + virtual const char* name() const noexcept; + /// Returns a static string describing the exception. + + virtual const char* className() const noexcept; + /// Returns the name of the exception class. + + virtual const char* what() const noexcept; + /// Returns a static string describing the exception. + /// + /// Same as name(), but for compatibility with std::exception. + + const Exception* nested() const; + /// Returns a pointer to the nested exception, or + /// null if no nested exception exists. + + const std::string& message() const; + /// Returns the message text. + + int code() const; + /// Returns the exception code if defined. + + virtual std::string displayText() const; + /// Returns a string consisting of the + /// message name and the message text. + + virtual Exception* clone() const; + /// Creates an exact copy of the exception. + /// + /// The copy can later be thrown again by + /// invoking rethrow() on it. + + virtual void rethrow() const; + /// (Re)Throws the exception. + /// + /// This is useful for temporarily storing a + /// copy of an exception (see clone()), then + /// throwing it again. + +protected: + Exception(int code = 0); + /// Standard constructor. + + void message(const std::string& msg); + /// Sets the message for the exception. + + void extendedMessage(const std::string& arg); + /// Sets the extended message for the exception. + +private: + std::string _msg; + Exception* _pNested; + int _code; +}; + + +// +// inlines +// +inline const Exception* Exception::nested() const +{ + return _pNested; +} + + +inline const std::string& Exception::message() const +{ + return _msg; +} + + +inline void Exception::message(const std::string& msg) +{ + _msg = msg; +} + + +inline int Exception::code() const +{ + return _code; +} + + +// +// Macros for quickly declaring and implementing exception classes. +// Unfortunately, we cannot use a template here because character +// pointers (which we need for specifying the exception name) +// are not allowed as template arguments. +// +#define POCO_DECLARE_EXCEPTION_CODE(API, CLS, BASE, CODE) \ + class API CLS: public BASE \ + { \ + public: \ + CLS(int code = CODE); \ + CLS(const std::string& msg, int code = CODE); \ + CLS(const std::string& msg, const std::string& arg, int code = CODE); \ + CLS(const std::string& msg, const Poco::Exception& exc, int code = CODE); \ + CLS(const CLS& exc); \ + ~CLS() noexcept; \ + CLS& operator = (const CLS& exc); \ + const char* name() const noexcept; \ + const char* className() const noexcept; \ + Poco::Exception* clone() const; \ + void rethrow() const; \ + }; + +#define POCO_DECLARE_EXCEPTION(API, CLS, BASE) \ + POCO_DECLARE_EXCEPTION_CODE(API, CLS, BASE, 0) + +#define POCO_IMPLEMENT_EXCEPTION(CLS, BASE, NAME) \ + CLS::CLS(int otherCode): BASE(otherCode) \ + { \ + } \ + CLS::CLS(const std::string& msg, int otherCode): BASE(msg, otherCode) \ + { \ + } \ + CLS::CLS(const std::string& msg, const std::string& arg, int otherCode): BASE(msg, arg, otherCode) \ + { \ + } \ + CLS::CLS(const std::string& msg, const Poco::Exception& exc, int otherCode): BASE(msg, exc, otherCode) \ + { \ + } \ + CLS::CLS(const CLS& exc): BASE(exc) \ + { \ + } \ + CLS::~CLS() noexcept \ + { \ + } \ + CLS& CLS::operator = (const CLS& exc) \ + { \ + BASE::operator = (exc); \ + return *this; \ + } \ + const char* CLS::name() const noexcept \ + { \ + return NAME; \ + } \ + const char* CLS::className() const noexcept \ + { \ + return typeid(*this).name(); \ + } \ + Poco::Exception* CLS::clone() const \ + { \ + return new CLS(*this); \ + } \ + void CLS::rethrow() const \ + { \ + throw *this; \ + } + + +// +// Standard exception classes +// +POCO_DECLARE_EXCEPTION(Foundation_API, LogicException, Exception) +POCO_DECLARE_EXCEPTION(Foundation_API, AssertionViolationException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, NullPointerException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, NullValueException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, BugcheckException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, InvalidArgumentException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, NotImplementedException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, RangeException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, IllegalStateException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, InvalidAccessException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, SignalException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, UnhandledException, LogicException) + +POCO_DECLARE_EXCEPTION(Foundation_API, RuntimeException, Exception) +POCO_DECLARE_EXCEPTION(Foundation_API, NotFoundException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, ExistsException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, TimeoutException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, SystemException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, RegularExpressionException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, LibraryLoadException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, LibraryAlreadyLoadedException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, NoThreadAvailableException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, PropertyNotSupportedException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, PoolOverflowException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, NoPermissionException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, OutOfMemoryException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, DataException, RuntimeException) + +POCO_DECLARE_EXCEPTION(Foundation_API, DataFormatException, DataException) +POCO_DECLARE_EXCEPTION(Foundation_API, SyntaxException, DataException) +POCO_DECLARE_EXCEPTION(Foundation_API, CircularReferenceException, DataException) +POCO_DECLARE_EXCEPTION(Foundation_API, PathSyntaxException, SyntaxException) +POCO_DECLARE_EXCEPTION(Foundation_API, IOException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, ProtocolException, IOException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileException, IOException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileExistsException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileNotFoundException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, PathNotFoundException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileReadOnlyException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileAccessDeniedException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, CreateFileException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, OpenFileException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, WriteFileException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, ReadFileException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, DirectoryNotEmptyException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, UnknownURISchemeException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, TooManyURIRedirectsException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, URISyntaxException, SyntaxException) + +POCO_DECLARE_EXCEPTION(Foundation_API, ApplicationException, Exception) +POCO_DECLARE_EXCEPTION(Foundation_API, BadCastException, RuntimeException) + + +} // namespace Poco + + +#endif // Foundation_Exception_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ExpirationDecorator.h b/contrib/libs/poco/Foundation/include/Poco/ExpirationDecorator.h new file mode 100644 index 0000000000..2e9d40a638 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ExpirationDecorator.h @@ -0,0 +1,92 @@ +// +// ExpirationDecorator.h +// +// Library: Foundation +// Package: Events +// Module: ExpirationDecorator +// +// Implementation of the ExpirationDecorator template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ExpirationDecorator_INCLUDED +#define Foundation_ExpirationDecorator_INCLUDED + + +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" + + +namespace Poco { + + +template <typename TArgs> +class ExpirationDecorator + /// ExpirationDecorator adds an expiration method to values so that they can be used + /// with the UniqueExpireCache. +{ +public: + ExpirationDecorator(): + _value(), + _expiresAt() + { + } + + ExpirationDecorator(const TArgs& p, const Poco::Timespan::TimeDiff& diffInMs): + /// Creates an element that will expire in diff milliseconds + _value(p), + _expiresAt() + { + _expiresAt += (diffInMs*1000); + } + + ExpirationDecorator(const TArgs& p, const Poco::Timespan& timeSpan): + /// Creates an element that will expire after the given timeSpan + _value(p), + _expiresAt() + { + _expiresAt += timeSpan.totalMicroseconds(); + } + + ExpirationDecorator(const TArgs& p, const Poco::Timestamp& timeStamp): + /// Creates an element that will expire at the given time point + _value(p), + _expiresAt(timeStamp) + { + } + + + ~ExpirationDecorator() + { + } + + const Poco::Timestamp& getExpiration() const + { + return _expiresAt; + } + + const TArgs& value() const + { + return _value; + } + + TArgs& value() + { + return _value; + } + +private: + TArgs _value; + Timestamp _expiresAt; +}; + + +} // namespace Poco + + +#endif // Foundation_ExpirationDecorator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Expire.h b/contrib/libs/poco/Foundation/include/Poco/Expire.h new file mode 100644 index 0000000000..73f82b4b0d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Expire.h @@ -0,0 +1,194 @@ +// +// Expire.h +// +// Library: Foundation +// Package: Events +// Module: Expire +// +// Implementation of the Expire template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Expire_INCLUDED +#define Foundation_Expire_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractDelegate.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +template <class TArgs> +class Expire: public AbstractDelegate<TArgs> + /// Decorator for AbstractDelegate adding automatic + /// expiration of registrations to AbstractDelegate's. +{ +public: + Expire(const AbstractDelegate<TArgs>& p, Timestamp::TimeDiff expireMillisecs): + _pDelegate(p.clone()), + _expire(expireMillisecs*1000) + { + } + + Expire(const Expire& expire): + AbstractDelegate<TArgs>(expire), + _pDelegate(expire._pDelegate->clone()), + _expire(expire._expire), + _creationTime(expire._creationTime) + { + } + + ~Expire() + { + delete _pDelegate; + } + + Expire& operator = (const Expire& expire) + { + if (&expire != this) + { + delete this->_pDelegate; + this->_pDelegate = expire._pDelegate->clone(); + this->_expire = expire._expire; + this->_creationTime = expire._creationTime; + this->_pTarget = expire._pTarget; + } + return *this; + } + + bool notify(const void* sender, TArgs& arguments) + { + if (!expired()) + return this->_pDelegate->notify(sender, arguments); + else + return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + return other.equals(*_pDelegate); + } + + AbstractDelegate<TArgs>* clone() const + { + return new Expire(*this); + } + + void disable() + { + _pDelegate->disable(); + } + + const AbstractDelegate<TArgs>* unwrap() const + { + return this->_pDelegate; + } + +protected: + bool expired() const + { + return _creationTime.isElapsed(_expire); + } + + AbstractDelegate<TArgs>* _pDelegate; + Timestamp::TimeDiff _expire; + Timestamp _creationTime; + +private: + Expire(); +}; + + +template <> +class Expire<void>: public AbstractDelegate<void> + /// Decorator for AbstractDelegate adding automatic + /// expiration of registrations to AbstractDelegate's. +{ +public: + Expire(const AbstractDelegate<void>& p, Timestamp::TimeDiff expireMillisecs): + _pDelegate(p.clone()), + _expire(expireMillisecs*1000) + { + } + + Expire(const Expire& expire): + AbstractDelegate<void>(expire), + _pDelegate(expire._pDelegate->clone()), + _expire(expire._expire), + _creationTime(expire._creationTime) + { + } + + ~Expire() + { + delete _pDelegate; + } + + Expire& operator = (const Expire& expire) + { + if (&expire != this) + { + delete this->_pDelegate; + this->_pDelegate = expire._pDelegate->clone(); + this->_expire = expire._expire; + this->_creationTime = expire._creationTime; + //this->_pTarget = expire._pTarget; + } + return *this; + } + + bool notify(const void* sender) + { + if (!expired()) + return this->_pDelegate->notify(sender); + else + return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + return other.equals(*_pDelegate); + } + + AbstractDelegate<void>* clone() const + { + return new Expire(*this); + } + + void disable() + { + _pDelegate->disable(); + } + + const AbstractDelegate<void>* unwrap() const + { + return this->_pDelegate; + } + +protected: + bool expired() const + { + return _creationTime.isElapsed(_expire); + } + + AbstractDelegate<void>* _pDelegate; + Timestamp::TimeDiff _expire; + Timestamp _creationTime; + +private: + Expire(); +}; + + +} // namespace Poco + + +#endif // Foundation_Expire_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ExpireCache.h b/contrib/libs/poco/Foundation/include/Poco/ExpireCache.h new file mode 100644 index 0000000000..41f0482b30 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ExpireCache.h @@ -0,0 +1,65 @@ +// +// ExpireCache.h +// +// Library: Foundation +// Package: Cache +// Module: ExpireCache +// +// Definition of the ExpireCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ExpireCache_INCLUDED +#define Foundation_ExpireCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/ExpireStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class ExpireCache: public AbstractCache<TKey, TValue, ExpireStrategy<TKey, TValue>, TMutex, TEventMutex> + /// An ExpireCache caches entries for a fixed time period (per default 10 minutes). + /// Entries expire independently of the access pattern, i.e. after a constant time. + /// If you require your objects to expire after they were not accessed for a given time + /// period use a Poco::AccessExpireCache. + /// + /// Be careful when using an ExpireCache. A cache is often used + /// like cache.has(x) followed by cache.get x). Note that it could happen + /// that the "has" call works, then the current execution thread gets descheduled, time passes, + /// the entry gets invalid, thus leading to an empty SharedPtr being returned + /// when "get" is invoked. +{ +public: + ExpireCache(Timestamp::TimeDiff expire = 600000): + AbstractCache<TKey, TValue, ExpireStrategy<TKey, TValue>, TMutex, TEventMutex>(ExpireStrategy<TKey, TValue>(expire)) + { + } + + ~ExpireCache() + { + } + +private: + ExpireCache(const ExpireCache& aCache); + ExpireCache& operator = (const ExpireCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_ExpireCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ExpireLRUCache.h b/contrib/libs/poco/Foundation/include/Poco/ExpireLRUCache.h new file mode 100644 index 0000000000..d79281a8e8 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ExpireLRUCache.h @@ -0,0 +1,62 @@ +// +// ExpireLRUCache.h +// +// Library: Foundation +// Package: Cache +// Module: ExpireLRUCache +// +// Definition of the ExpireLRUCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ExpireLRUCache_INCLUDED +#define Foundation_ExpireLRUCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/StrategyCollection.h" +#include "Poco/ExpireStrategy.h" +#include "Poco/LRUStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class ExpireLRUCache: public AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue>, TMutex, TEventMutex> + /// An ExpireLRUCache combines LRU caching and time based expire caching. + /// It cache entries for a fixed time period (per default 10 minutes) + /// but also limits the size of the cache (per default: 1024). +{ +public: + ExpireLRUCache(long cacheSize = 1024, Timestamp::TimeDiff expire = 600000): + AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue>, TMutex, TEventMutex>(StrategyCollection<TKey, TValue>()) + { + this->_strategy.pushBack(new LRUStrategy<TKey, TValue>(cacheSize)); + this->_strategy.pushBack(new ExpireStrategy<TKey, TValue>(expire)); + } + + ~ExpireLRUCache() + { + } + +private: + ExpireLRUCache(const ExpireLRUCache& aCache); + ExpireLRUCache& operator = (const ExpireLRUCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_ExpireLRUCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ExpireStrategy.h b/contrib/libs/poco/Foundation/include/Poco/ExpireStrategy.h new file mode 100644 index 0000000000..40e49eae8c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ExpireStrategy.h @@ -0,0 +1,132 @@ +// +// ExpireStrategy.h +// +// Library: Foundation +// Package: Cache +// Module: ExpireStrategy +// +// Definition of the ExpireStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ExpireStrategy_INCLUDED +#define Foundation_ExpireStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/AbstractStrategy.h" +#include "Poco/Bugcheck.h" +#include "Poco/Timestamp.h" +#include "Poco/EventArgs.h" +#include <set> +#include <map> + + +namespace Poco { + + +template < + class TKey, + class TValue +> +class ExpireStrategy: public AbstractStrategy<TKey, TValue> + /// An ExpireStrategy implements time based expiration of cache entries +{ +public: + typedef std::multimap<Timestamp, TKey> TimeIndex; + typedef typename TimeIndex::iterator IndexIterator; + typedef typename TimeIndex::const_iterator ConstIndexIterator; + typedef std::map<TKey, IndexIterator> Keys; + typedef typename Keys::iterator Iterator; + +public: + ExpireStrategy(Timestamp::TimeDiff expireTimeInMilliSec): _expireTime(expireTimeInMilliSec * 1000) + /// Create an expire strategy. Note that the smallest allowed caching time is 25ms. + /// Anything lower than that is not useful with current operating systems. + { + if (_expireTime < 25000) throw InvalidArgumentException("expireTime must be at least 25 ms"); + } + + ~ExpireStrategy() + { + } + + void onAdd(const void*, const KeyValueArgs <TKey, TValue>& args) + { + Timestamp now; + typename TimeIndex::value_type tiValue(now, args.key()); + IndexIterator it = _keyIndex.insert(tiValue); + typename Keys::value_type kValue(args.key(), it); + std::pair<Iterator, bool> stat = _keys.insert(kValue); + if (!stat.second) + { + _keyIndex.erase(stat.first->second); + stat.first->second = it; + } + } + + void onRemove(const void*, const TKey& key) + { + Iterator it = _keys.find(key); + if (it != _keys.end()) + { + _keyIndex.erase(it->second); + _keys.erase(it); + } + } + + void onGet(const void*, const TKey& /*key*/) + { + // get triggers no changes in an expire + } + + void onClear(const void*, const EventArgs& /*args*/) + { + _keys.clear(); + _keyIndex.clear(); + } + + void onIsValid(const void*, ValidArgs<TKey>& args) + { + Iterator it = _keys.find(args.key()); + if (it != _keys.end()) + { + if (it->second->first.isElapsed(_expireTime)) + { + args.invalidate(); + } + } + else //not found: probably removed by onReplace + args.invalidate(); + } + + void onReplace(const void*, std::set<TKey>& elemsToRemove) + { + // Note: replace only informs the cache which elements + // it would like to remove! + // it does not remove them on its own! + IndexIterator it = _keyIndex.begin(); + while (it != _keyIndex.end() && it->first.isElapsed(_expireTime)) + { + elemsToRemove.insert(it->second); + ++it; + } + } + +protected: + Timestamp::TimeDiff _expireTime; + Keys _keys; /// For faster replacement of keys, the iterator points to the _keyIndex map + TimeIndex _keyIndex; /// Maps time to key value +}; + + +} // namespace Poco + + +#endif // Foundation_ExpireStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FIFOBuffer.h b/contrib/libs/poco/Foundation/include/Poco/FIFOBuffer.h new file mode 100644 index 0000000000..8382b753b5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FIFOBuffer.h @@ -0,0 +1,556 @@ +// +// FIFOBuffer.h +// +// Library: Foundation +// Package: Core +// Module: FIFOBuffer +// +// Definition of the FIFOBuffer class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FIFOBuffer_INCLUDED +#define Foundation_FIFOBuffer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/Buffer.h" +#include "Poco/BasicEvent.h" +#include "Poco/Mutex.h" +#include "Poco/Format.h" + + +namespace Poco { + + +template <class T> +class BasicFIFOBuffer + /// A simple buffer class with support for re-entrant, + /// FIFO-style read/write operations, as well as (optional) + /// empty/non-empty/full (i.e. writable/readable) transition + /// notifications. Buffer can be flagged with end-of-file and + /// error flags, which renders it un-readable/writable. + /// + /// Critical portions of code are protected by a recursive mutex. + /// However, to achieve thread-safety in cases where multiple + /// member function calls are involved and have to be atomic, + /// the mutex must be locked externally. + /// + /// Buffer size, as well as amount of unread data and + /// available space introspections are supported as well. + /// + /// This class is useful anywhere where a FIFO functionality + /// is needed. +{ +public: + typedef T Type; + + mutable Poco::BasicEvent<bool> writable; + /// Event indicating "writability" of the buffer, + /// triggered as follows: + /// + /// * when buffer transitions from non-full to full, + /// Writable event observers are notified, with + /// false value as the argument + /// + /// * when buffer transitions from full to non-full, + /// Writable event observers are notified, with + /// true value as the argument + + mutable Poco::BasicEvent<bool> readable; + /// Event indicating "readability" of the buffer, + /// triggered as follows: + /// + /// * when buffer transitions from non-empty to empty, + /// Readable event observers are notified, with false + /// value as the argument + /// + /// * when FIFOBuffer transitions from empty to non-empty, + /// Readable event observers are notified, with true value + /// as the argument + + BasicFIFOBuffer(std::size_t bufferSize, bool bufferNotify = false): + _buffer(bufferSize), + _begin(0), + _used(0), + _notify(bufferNotify), + _eof(false), + _error(false) + /// Creates the FIFOBuffer. + { + } + + BasicFIFOBuffer(T* pBuffer, std::size_t bufferSize, bool bufferNotify = false): + _buffer(pBuffer, bufferSize), + _begin(0), + _used(0), + _notify(bufferNotify), + _eof(false), + _error(false) + /// Creates the FIFOBuffer. + { + } + + BasicFIFOBuffer(const T* pBuffer, std::size_t bufferSize, bool bufferNotify = false): + _buffer(pBuffer, bufferSize), + _begin(0), + _used(bufferSize), + _notify(bufferNotify), + _eof(false), + _error(false) + /// Creates the FIFOBuffer. + { + } + + ~BasicFIFOBuffer() + /// Destroys the FIFOBuffer. + { + } + + void resize(std::size_t newSize, bool preserveContent = true) + /// Resizes the buffer. If preserveContent is true, + /// the content of the old buffer is preserved. + /// New size can be larger or smaller than + /// the current size, but it must not be 0. + /// Additionally, if the new length is smaller + /// than currently used length and preserveContent + /// is true, InvalidAccessException is thrown. + { + Mutex::ScopedLock lock(_mutex); + + if (preserveContent && (newSize < _used)) + throw InvalidAccessException("Can not resize FIFO without data loss."); + + std::size_t usedBefore = _used; + _buffer.resize(newSize, preserveContent); + if (!preserveContent) _used = 0; + if (_notify) notify(usedBefore); + } + + std::size_t peek(T* pBuffer, std::size_t length) const + /// Peeks into the data currently in the FIFO + /// without actually extracting it. + /// If length is zero, the return is immediate. + /// If length is greater than used length, + /// it is substituted with the the current FIFO + /// used length. + /// + /// Returns the number of elements copied in the + /// supplied buffer. + { + if (0 == length) return 0; + Mutex::ScopedLock lock(_mutex); + if (!isReadable()) return 0; + if (length > _used) length = _used; + std::memcpy(pBuffer, _buffer.begin() + _begin, length * sizeof(T)); + return length; + } + + std::size_t peek(Poco::Buffer<T>& rBuffer, std::size_t length = 0) const + /// Peeks into the data currently in the FIFO + /// without actually extracting it. + /// Resizes the supplied buffer to the size of + /// data written to it. If length is not + /// supplied by the caller or is greater than length + /// of currently used data, the current FIFO used + /// data length is substituted for it. + /// + /// Returns the number of elements copied in the + /// supplied buffer. + { + Mutex::ScopedLock lock(_mutex); + if (!isReadable()) return 0; + if (0 == length || length > _used) length = _used; + rBuffer.resize(length); + return peek(rBuffer.begin(), length); + } + + std::size_t read(T* pBuffer, std::size_t length) + /// Copies the data currently in the FIFO + /// into the supplied buffer, which must be + /// preallocated to at least the length size + /// before calling this function. + /// + /// Returns the size of the copied data. + { + if (0 == length) return 0; + Mutex::ScopedLock lock(_mutex); + if (!isReadable()) return 0; + std::size_t usedBefore = _used; + std::size_t readLen = peek(pBuffer, length); + poco_assert (_used >= readLen); + _used -= readLen; + if (0 == _used) _begin = 0; + else _begin += length; + + if (_notify) notify(usedBefore); + + return readLen; + } + + std::size_t read(Poco::Buffer<T>& rBuffer, std::size_t length = 0) + /// Copies the data currently in the FIFO + /// into the supplied buffer. + /// Resizes the supplied buffer to the size of + /// data written to it. + /// + /// Returns the size of the copied data. + { + Mutex::ScopedLock lock(_mutex); + if (!isReadable()) return 0; + std::size_t usedBefore = _used; + std::size_t readLen = peek(rBuffer, length); + poco_assert (_used >= readLen); + _used -= readLen; + if (0 == _used) _begin = 0; + else _begin += length; + + if (_notify) notify(usedBefore); + + return readLen; + } + + std::size_t write(const T* pBuffer, std::size_t length) + /// Writes data from supplied buffer to the FIFO buffer. + /// If there is no sufficient space for the whole + /// buffer to be written, data up to available + /// length is written. + /// The length of data to be written is determined from the + /// length argument. Function does nothing and returns zero + /// if length argument is equal to zero. + /// + /// Returns the length of data written. + { + if (0 == length) return 0; + + Mutex::ScopedLock lock(_mutex); + + if (!isWritable()) return 0; + + if (_buffer.size() - (_begin + _used) < length) + { + std::memmove(_buffer.begin(), begin(), _used * sizeof(T)); + _begin = 0; + } + + std::size_t usedBefore = _used; + std::size_t availableBefore = _buffer.size() - _used - _begin; + std::size_t len = length > availableBefore ? availableBefore : length; + std::memcpy(begin() + _used, pBuffer, len * sizeof(T)); + _used += len; + poco_assert (_used <= _buffer.size()); + if (_notify) notify(usedBefore); + + return len; + } + + std::size_t write(const Buffer<T>& rBuffer, std::size_t length = 0) + /// Writes data from supplied buffer to the FIFO buffer. + /// If there is no sufficient space for the whole + /// buffer to be written, data up to available + /// length is written. + /// The length of data to be written is determined from the + /// length argument or buffer size (when length argument is + /// default zero or greater than buffer size). + /// + /// Returns the length of data written. + { + if (length == 0 || length > rBuffer.size()) + length = rBuffer.size(); + + return write(rBuffer.begin(), length); + } + + std::size_t size() const + /// Returns the size of the buffer. + { + return _buffer.size(); + } + + std::size_t used() const + /// Returns the size of the used portion of the buffer. + { + return _used; + } + + std::size_t available() const + /// Returns the size of the available portion of the buffer. + { + return size() - _used; + } + + void drain(std::size_t length = 0) + /// Drains length number of elements from the buffer. + /// If length is zero or greater than buffer current + /// content length, buffer is emptied. + { + Mutex::ScopedLock lock(_mutex); + + std::size_t usedBefore = _used; + + if (0 == length || length >= _used) + { + _begin = 0; + _used = 0; + } + else + { + _begin += length; + _used -= length; + } + + if (_notify) notify(usedBefore); + } + + void copy(const T* ptr, std::size_t length) + /// Copies the supplied data to the buffer and adjusts + /// the used buffer size. + { + poco_check_ptr(ptr); + if (0 == length) return; + + Mutex::ScopedLock lock(_mutex); + + if (length > available()) + throw Poco::InvalidAccessException("Cannot extend buffer."); + + if (!isWritable()) + throw Poco::InvalidAccessException("Buffer not writable."); + + std::memcpy(begin() + _used, ptr, length * sizeof(T)); + std::size_t usedBefore = _used; + _used += length; + if (_notify) notify(usedBefore); + } + + void advance(std::size_t length) + /// Advances buffer by length elements. + /// Should be called AFTER the data + /// was copied into the buffer. + { + Mutex::ScopedLock lock(_mutex); + + if (length > available()) + throw Poco::InvalidAccessException("Cannot extend buffer."); + + if (!isWritable()) + throw Poco::InvalidAccessException("Buffer not writable."); + + if (_buffer.size() - (_begin + _used) < length) + { + std::memmove(_buffer.begin(), begin(), _used * sizeof(T)); + _begin = 0; + } + + std::size_t usedBefore = _used; + _used += length; + if (_notify) notify(usedBefore); + } + + T* begin() + /// Returns the pointer to the beginning of the buffer. + { + Mutex::ScopedLock lock(_mutex); + if (_begin != 0) + { + // Move the data to the start of the buffer so begin() and next() + // always return consistent pointers with each other and allow writing + // to the end of the buffer. + std::memmove(_buffer.begin(), _buffer.begin() + _begin, _used * sizeof(T)); + _begin = 0; + } + return _buffer.begin(); + } + + T* next() + /// Returns the pointer to the next available position in the buffer. + { + Mutex::ScopedLock lock(_mutex); + return begin() + _used; + } + + T& operator [] (std::size_t index) + /// Returns value at index position. + /// Throws InvalidAccessException if index is larger than + /// the last valid (used) buffer position. + { + Mutex::ScopedLock lock(_mutex); + if (index >= _used) + throw InvalidAccessException(format("Index out of bounds: %z (max index allowed: %z)", index, _used - 1)); + + return _buffer[_begin + index]; + } + + const T& operator [] (std::size_t index) const + /// Returns value at index position. + /// Throws InvalidAccessException if index is larger than + /// the last valid (used) buffer position. + { + Mutex::ScopedLock lock(_mutex); + if (index >= _used) + throw InvalidAccessException(format("Index out of bounds: %z (max index allowed: %z)", index, _used - 1)); + + return _buffer[_begin + index]; + } + + const Buffer<T>& buffer() const + /// Returns const reference to the underlying buffer. + { + return _buffer; + } + + void setError(bool error = true) + /// Sets the error flag on the buffer and empties it. + /// If notifications are enabled, they will be triggered + /// if appropriate. + /// + /// Setting error flag to true prevents reading and writing + /// to the buffer; to re-enable FIFOBuffer for reading/writing, + /// the error flag must be set to false. + { + if (error) + { + bool f = false; + Mutex::ScopedLock lock(_mutex); + if (error && isReadable() && _notify) readable.notify(this, f); + if (error && isWritable() && _notify) writable.notify(this, f); + _error = error; + _used = 0; + } + else + { + bool t = true; + Mutex::ScopedLock lock(_mutex); + _error = false; + if (_notify && !_eof) writable.notify(this, t); + } + } + + bool isValid() const + /// Returns true if error flag is not set on the buffer, + /// otherwise returns false. + { + return !_error; + } + + void setEOF(bool eof = true) + /// Sets end-of-file flag on the buffer. + /// + /// Setting EOF flag to true prevents writing to the + /// buffer; reading from the buffer will still be + /// allowed until all data present in the buffer at the + /// EOF set time is drained. After that, to re-enable + /// FIFOBuffer for reading/writing, EOF must be + /// set to false. + /// + /// Setting EOF flag to false clears EOF state if it + /// was previously set. If EOF was not set, it has no + /// effect. + { + Mutex::ScopedLock lock(_mutex); + bool flag = !eof; + if (_notify) writable.notify(this, flag); + _eof = eof; + } + + bool hasEOF() const + /// Returns true if EOF flag has been set. + { + return _eof; + } + + bool isEOF() const + /// Returns true if EOF flag has been set and buffer is empty. + { + return isEmpty() && _eof; + } + + bool isEmpty() const + /// Returns true is buffer is empty, false otherwise. + { + return 0 == _used; + } + + bool isFull() const + /// Returns true is buffer is full, false otherwise. + { + return size() == _used; + } + + bool isReadable() const + /// Returns true if buffer contains data and is not + /// in error state. + { + return !isEmpty() && isValid(); + } + + bool isWritable() const + /// Returns true if buffer is not full and is not + /// in error state. + { + return !isFull() && isValid() && !_eof; + } + + void setNotify(bool bufferNotify = true) + /// Enables/disables notifications. + { + _notify = bufferNotify; + } + + bool getNotify() const + /// Returns true if notifications are enabled, false otherwise. + { + return _notify; + } + + Mutex& mutex() + /// Returns reference to mutex. + { + return _mutex; + } + +private: + void notify(std::size_t usedBefore) + { + bool t = true, f = false; + if (usedBefore == 0 && _used > 0) + readable.notify(this, t); + else if (usedBefore > 0 && 0 == _used) + readable.notify(this, f); + + if (usedBefore == _buffer.size() && _used < _buffer.size()) + writable.notify(this, t); + else if (usedBefore < _buffer.size() && _used == _buffer.size()) + writable.notify(this, f); + } + + BasicFIFOBuffer(); + BasicFIFOBuffer(const BasicFIFOBuffer&); + BasicFIFOBuffer& operator = (const BasicFIFOBuffer&); + + Buffer<T> _buffer; + std::size_t _begin; + std::size_t _used; + bool _notify; + mutable Mutex _mutex; + bool _eof; + bool _error; +}; + + +// +// We provide an instantiation for char +// +typedef BasicFIFOBuffer<char> FIFOBuffer; + + +} // namespace Poco + + +#endif // Foundation_FIFOBuffer_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FIFOBufferStream.h b/contrib/libs/poco/Foundation/include/Poco/FIFOBufferStream.h new file mode 100644 index 0000000000..6c1e1eb787 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FIFOBufferStream.h @@ -0,0 +1,154 @@ +// +// FIFOBufferStream.h +// +// Library: Foundation +// Package: Streams +// Module: FIFOBufferStream +// +// Definition of the FIFOBufferStream class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FIFOBufferStream_INCLUDED +#define Foundation_FIFOBufferStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/FIFOBuffer.h" +#include "Poco/BufferedBidirectionalStreamBuf.h" +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API FIFOBufferStreamBuf: public BufferedBidirectionalStreamBuf + /// This is the streambuf class used for reading from and writing to a FIFOBuffer. + /// FIFOBuffer is enabled for emtpy/non-empty/full state transitions notifications. +{ +public: + + FIFOBufferStreamBuf(); + /// Creates a FIFOBufferStreamBuf. + + explicit FIFOBufferStreamBuf(FIFOBuffer& fifoBuffer); + /// Creates a FIFOBufferStreamBuf and assigns the given buffer to it. + + FIFOBufferStreamBuf(char* pBuffer, std::size_t length); + /// Creates a FIFOBufferStreamBuf and assigns the given buffer to it. + + FIFOBufferStreamBuf(const char* pBuffer, std::size_t length); + /// Creates a FIFOBufferStreamBuf and assigns the given buffer to it. + + explicit FIFOBufferStreamBuf(std::size_t length); + /// Creates a FIFOBufferStreamBuf of the given length. + + ~FIFOBufferStreamBuf(); + /// Destroys the FIFOBufferStreamBuf. + + FIFOBuffer& fifoBuffer(); + /// Returns the underlying FIFO buffer reference. + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024 + }; + + FIFOBuffer* _pFIFOBuffer; + FIFOBuffer& _fifoBuffer; +}; + + +class Foundation_API FIFOIOS: public virtual std::ios + /// The base class for FIFOBufferInputStream and + /// FIFOBufferStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + explicit FIFOIOS(FIFOBuffer& buffer); + /// Creates a FIFOIOS and assigns the given buffer to it. + + FIFOIOS(char* pBuffer, std::size_t length); + /// Creates a FIFOIOS and assigns the given buffer to it. + + FIFOIOS(const char* pBuffer, std::size_t length); + /// Creates a FIFOIOS and assigns the given buffer to it. + + explicit FIFOIOS(std::size_t length); + /// Creates a FIFOIOS of the given length. + + ~FIFOIOS(); + /// Destroys the FIFOIOS. + /// + /// Flushes the buffer. + + FIFOBufferStreamBuf* rdbuf(); + /// Returns a pointer to the internal FIFOBufferStreamBuf. + + void close(); + /// Flushes the stream. + +protected: + FIFOBufferStreamBuf _buf; +}; + + +class Foundation_API FIFOBufferStream: public FIFOIOS, public std::iostream + /// An output stream for writing to a FIFO. +{ +public: + Poco::BasicEvent<bool>& readable; + Poco::BasicEvent<bool>& writable; + + explicit FIFOBufferStream(FIFOBuffer& buffer); + /// Creates the FIFOBufferStream with supplied buffer as initial value. + + FIFOBufferStream(char* pBuffer, std::size_t length); + /// Creates a FIFOBufferStream and assigns the given buffer to it. + + FIFOBufferStream(const char* pBuffer, std::size_t length); + /// Creates a FIFOBufferStream and assigns the given buffer to it. + + explicit FIFOBufferStream(std::size_t length); + /// Creates a FIFOBufferStream of the given length. + + ~FIFOBufferStream(); + /// Destroys the FIFOBufferStream. + /// + /// Flushes the buffer. + +private: + FIFOBufferStream(); + FIFOBufferStream(const FIFOBufferStream& other); + FIFOBufferStream& operator =(const FIFOBufferStream& other); +}; + + +/// +/// inlines +/// + + +inline FIFOBuffer& FIFOBufferStreamBuf::fifoBuffer() +{ + return _fifoBuffer; +} + + +} // namespace Poco + + +#endif // Foundation_FIFOBufferStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FIFOEvent.h b/contrib/libs/poco/Foundation/include/Poco/FIFOEvent.h new file mode 100644 index 0000000000..404044c392 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FIFOEvent.h @@ -0,0 +1,63 @@ +// +// FIFOEvent.h +// +// Library: Foundation +// Package: Events +// Module: FIFOEvent +// +// Implementation of the FIFOEvent template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FIFOEvent_INCLUDED +#define Foundation_FIFOEvent_INCLUDED + + +#include "Poco/AbstractEvent.h" +#include "Poco/FIFOStrategy.h" +#include "Poco/AbstractDelegate.h" + + +namespace Poco { + + +//@ deprecated +template <class TArgs, class TMutex = FastMutex> +class FIFOEvent: public AbstractEvent < + TArgs, + FIFOStrategy<TArgs, AbstractDelegate<TArgs> >, + AbstractDelegate<TArgs>, + TMutex +> + /// A FIFOEvent uses internally a FIFOStrategy which guarantees + /// that delegates are invoked in the order they were added to + /// the event. + /// + /// Note that as of release 1.4.2, this is the default behavior + /// implemented by BasicEvent, so this class is provided + /// for backwards compatibility only. +{ +public: + FIFOEvent() + { + } + + ~FIFOEvent() + { + } + +private: + FIFOEvent(const FIFOEvent& e); + FIFOEvent& operator = (const FIFOEvent& e); +}; + + +} // namespace Poco + + +#endif // Foundation_FIFOEvent_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FIFOStrategy.h b/contrib/libs/poco/Foundation/include/Poco/FIFOStrategy.h new file mode 100644 index 0000000000..79c2276043 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FIFOStrategy.h @@ -0,0 +1,59 @@ +// +// FIFOStrategy.h +// +// Library: Foundation +// Package: Events +// Module: FIFOStragegy +// +// Implementation of the FIFOStrategy template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FIFOStrategy_INCLUDED +#define Foundation_FIFOStrategy_INCLUDED + + +#include "Poco/DefaultStrategy.h" + + +namespace Poco { + + +//@ deprecated +template <class TArgs, class TDelegate> +class FIFOStrategy: public DefaultStrategy<TArgs, TDelegate> + /// Note: As of release 1.4.2, DefaultStrategy already + /// implements FIFO behavior, so this class is provided + /// for backwards compatibility only. +{ +public: + FIFOStrategy() + { + } + + FIFOStrategy(const FIFOStrategy& s): + DefaultStrategy<TArgs, TDelegate>(s) + { + } + + ~FIFOStrategy() + { + } + + FIFOStrategy& operator = (const FIFOStrategy& s) + { + DefaultStrategy<TArgs, TDelegate>::operator = (s); + return *this; + } +}; + + +} // namespace Poco + + +#endif // Foundation_FIFOStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FPEnvironment.h b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment.h new file mode 100644 index 0000000000..4602f57f91 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment.h @@ -0,0 +1,207 @@ +// +// FPEnvironment.h +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironment. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FPEnvironment_INCLUDED +#define Foundation_FPEnvironment_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_NO_FPENVIRONMENT) +#include "Poco/FPEnvironment_DUMMY.h" +#elif defined(__osf__) +#include "Poco/FPEnvironment_DEC.h" +#elif defined(sun) || defined(__sun) +#include "Poco/FPEnvironment_SUN.h" +#elif defined(__QNX__) +#include "Poco/FPEnvironment_QNX.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/FPEnvironment_C99.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/FPEnvironment_WIN32.h" +#else +#include "Poco/FPEnvironment_DUMMY.h" +#endif + + +namespace Poco { + + +class Foundation_API FPEnvironment: private FPEnvironmentImpl + /// Instances of this class can be used to save + /// and later restore the current floating + /// point environment (consisting of rounding + /// mode and floating-point flags). + /// The class also provides various static + /// methods to query certain properties + /// of a floating-point number. +{ +public: + enum RoundingMode + { + FP_ROUND_DOWNWARD = FP_ROUND_DOWNWARD_IMPL, + FP_ROUND_UPWARD = FP_ROUND_UPWARD_IMPL, + FP_ROUND_TONEAREST = FP_ROUND_TONEAREST_IMPL, + FP_ROUND_TOWARDZERO = FP_ROUND_TOWARDZERO_IMPL + }; + + enum Flag + { + FP_DIVIDE_BY_ZERO = FP_DIVIDE_BY_ZERO_IMPL, + FP_INEXACT = FP_INEXACT_IMPL, + FP_OVERFLOW = FP_OVERFLOW_IMPL, + FP_UNDERFLOW = FP_UNDERFLOW_IMPL, + FP_INVALID = FP_INVALID_IMPL + }; + + FPEnvironment(); + /// Standard constructor. + /// Remembers the current environment. + + FPEnvironment(RoundingMode mode); + /// Remembers the current environment and + /// sets the given rounding mode. + + FPEnvironment(const FPEnvironment& env); + /// Copy constructor. + + ~FPEnvironment(); + /// Restores the previous environment (unless + /// keepCurrent() has been called previously) + + FPEnvironment& operator = (const FPEnvironment& env); + /// Assignment operator + + void keepCurrent(); + /// Keep the current environment even after + /// destroying the FPEnvironment object. + + static void clearFlags(); + /// Resets all flags. + + static bool isFlag(Flag flag); + /// Returns true iff the given flag is set. + + static void setRoundingMode(RoundingMode mode); + /// Sets the rounding mode. + + static RoundingMode getRoundingMode(); + /// Returns the current rounding mode. + + static bool isInfinite(float value); + static bool isInfinite(double value); + static bool isInfinite(long double value); + /// Returns true iff the given number is infinite. + + static bool isNaN(float value); + static bool isNaN(double value); + static bool isNaN(long double value); + /// Returns true iff the given number is NaN. + + static float copySign(float target, float source); + static double copySign(double target, double source); + static long double copySign(long double target, long double source); + /// Copies the sign from source to target. +}; + + +// +// For convenience, we provide a shorter name for +// the FPEnvironment class. +// +typedef FPEnvironment FPE; + + +// +// inline's +// +inline bool FPEnvironment::isFlag(Flag flag) +{ + return isFlagImpl(FlagImpl(flag)); +} + + +inline void FPEnvironment::setRoundingMode(RoundingMode mode) +{ + setRoundingModeImpl(RoundingModeImpl(mode)); +} + + +inline FPEnvironment::RoundingMode FPEnvironment::getRoundingMode() +{ + return RoundingMode(getRoundingModeImpl()); +} + + +inline bool FPEnvironment::isInfinite(float value) +{ + return isInfiniteImpl(value); +} + + +inline bool FPEnvironment::isInfinite(double value) +{ + return isInfiniteImpl(value); +} + + +inline bool FPEnvironment::isInfinite(long double value) +{ + return isInfiniteImpl(value); +} + + +inline bool FPEnvironment::isNaN(float value) +{ + return isNaNImpl(value); +} + + +inline bool FPEnvironment::isNaN(double value) +{ + return isNaNImpl(value); +} + + +inline bool FPEnvironment::isNaN(long double value) +{ + return isNaNImpl(value); +} + + +inline float FPEnvironment::copySign(float target, float source) +{ + return copySignImpl(target, source); +} + + +inline double FPEnvironment::copySign(double target, double source) +{ + return copySignImpl(target, source); +} + + +inline long double FPEnvironment::copySign(long double target, long double source) +{ + return copySignImpl(target, source); +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_C99.h b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_C99.h new file mode 100644 index 0000000000..0b192f5a1c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_C99.h @@ -0,0 +1,125 @@ +// +// FPEnvironment_C99.h +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for C99. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FPEnvironment_C99_INCLUDED +#define Foundation_FPEnvironment_C99_INCLUDED + + +#include "Poco/Foundation.h" +#include <fenv.h> +#include <cmath> + + +namespace Poco { + + +class FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = FE_DOWNWARD, + FP_ROUND_UPWARD_IMPL = FE_UPWARD, + FP_ROUND_TONEAREST_IMPL = FE_TONEAREST, + FP_ROUND_TOWARDZERO_IMPL = FE_TOWARDZERO + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL = FE_DIVBYZERO, + FP_INEXACT_IMPL = FE_INEXACT, + FP_OVERFLOW_IMPL = FE_OVERFLOW, + FP_UNDERFLOW_IMPL = FE_UNDERFLOW, + FP_INVALID_IMPL = FE_INVALID + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + fenv_t _env; +}; + + +// +// inlines +// +inline bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + return std::isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + return std::isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ + return std::isinf((double) value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(float value) +{ + return std::isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(double value) +{ + return std::isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(long double value) +{ + return std::isnan((double) value) != 0; +} + + +inline float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + return copysignf(target, source); +} + + +inline double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + return copysign(target, source); +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_C99_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_DEC.h b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_DEC.h new file mode 100644 index 0000000000..b55794a519 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_DEC.h @@ -0,0 +1,89 @@ +// +// FPEnvironment_DEC.h +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for Tru64 and OpenVMS Alpha. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FPEnvironment_DEC_INCLUDED +#define Foundation_FPEnvironment_DEC_INCLUDED + + +#include "Poco/Foundation.h" +#if defined(__VMS) +#include <ieeedef.h> +#else +#include <machine/fpu.h> +#endif + + +namespace Poco { + + +class FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = 0, + FP_ROUND_UPWARD_IMPL = 0, + FP_ROUND_TONEAREST_IMPL = 0, + FP_ROUND_TOWARDZERO_IMPL = 0 + }; + enum FlagImpl + { +#if defined(__VMS) + FP_DIVIDE_BY_ZERO_IMPL = IEEE$M_STATUS_DZE, + FP_INEXACT_IMPL = IEEE$M_STATUS_INE, + FP_OVERFLOW_IMPL = IEEE$M_STATUS_OVF, + FP_UNDERFLOW_IMPL = IEEE$M_STATUS_UNF, + FP_INVALID_IMPL = IEEE$M_STATUS_INV +#else + FP_DIVIDE_BY_ZERO_IMPL = IEEE_STATUS_DZE, + FP_INEXACT_IMPL = IEEE_STATUS_INE, + FP_OVERFLOW_IMPL = IEEE_STATUS_OVF, + FP_UNDERFLOW_IMPL = IEEE_STATUS_UNF, + FP_INVALID_IMPL = IEEE_STATUS_INV +#endif + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: +#if defined(__VMS) + struct _ieee _env; +#else + unsigned long _env; +#endif +}; + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_DEC_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_DUMMY.h b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_DUMMY.h new file mode 100644 index 0000000000..5571c128c2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_DUMMY.h @@ -0,0 +1,125 @@ +// +// FPEnvironment_DUMMY.h +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definition of class FPEnvironmentImpl for platforms that do not +// support IEEE 754 extensions. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FPEnvironment_DUMMY_INCLUDED +#define Foundation_FPEnvironment_DUMMY_INCLUDED + + +#include "Poco/Foundation.h" +#include <cmath> + + +namespace Poco { + + +class Foundation_API FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL, + FP_ROUND_UPWARD_IMPL, + FP_ROUND_TONEAREST_IMPL, + FP_ROUND_TOWARDZERO_IMPL + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL, + FP_INEXACT_IMPL, + FP_OVERFLOW_IMPL, + FP_UNDERFLOW_IMPL, + FP_INVALID_IMPL + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + static RoundingModeImpl _roundingMode; +}; + + +// +// inlines +// +inline bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + return std::isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + return std::isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ + return std::isinf((double) value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(float value) +{ + return std::isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(double value) +{ + return std::isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(long double value) +{ + return std::isnan((double) value) != 0; +} + + +inline float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + return copysignf(target, source); +} + + +inline double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + return copysign(target, source); +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_DUMMY_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_QNX.h b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_QNX.h new file mode 100644 index 0000000000..1eef8259d3 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_QNX.h @@ -0,0 +1,133 @@ +// +// FPEnvironment_QNX.h +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for QNX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FPEnvironment_QNX_INCLUDED +#define Foundation_FPEnvironment_QNX_INCLUDED + + +#include "Poco/Foundation.h" +#include <fenv.h> +#include <cmath> + + +namespace Poco { + + +class FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = FE_DOWNWARD, + FP_ROUND_UPWARD_IMPL = FE_UPWARD, + FP_ROUND_TONEAREST_IMPL = FE_TONEAREST, + FP_ROUND_TOWARDZERO_IMPL = FE_TOWARDZERO + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL = FE_DIVBYZERO, + FP_INEXACT_IMPL = FE_INEXACT, + FP_OVERFLOW_IMPL = FE_OVERFLOW, + FP_UNDERFLOW_IMPL = FE_UNDERFLOW, + FP_INVALID_IMPL = FE_INVALID + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + fenv_t _env; +}; + + +// +// inlines +// +inline bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + using namespace std; + return isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + using namespace std; + return isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ + using namespace std; + return isinf((double) value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(float value) +{ + using namespace std; + return isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(double value) +{ + using namespace std; + return isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(long double value) +{ + using namespace std; + return isnan((double) value) != 0; +} + + +inline float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + using namespace std; + return copysignf(target, source); +} + + +inline double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + using namespace std; + return copysign(target, source); +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_QNX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_SUN.h b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_SUN.h new file mode 100644 index 0000000000..d9755006d6 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_SUN.h @@ -0,0 +1,74 @@ +// +// FPEnvironment_SUN.h +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for Solaris. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FPEnvironment_SUN_INCLUDED +#define Foundation_FPEnvironment_SUN_INCLUDED + + +#include "Poco/Foundation.h" +#include <ieeefp.h> + + +namespace Poco { + + +class FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = FP_RM, + FP_ROUND_UPWARD_IMPL = FP_RP, + FP_ROUND_TONEAREST_IMPL = FP_RN, + FP_ROUND_TOWARDZERO_IMPL = FP_RZ + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL = FP_X_DZ, + FP_INEXACT_IMPL = FP_X_IMP, + FP_OVERFLOW_IMPL = FP_X_OFL, + FP_UNDERFLOW_IMPL = FP_X_UFL, + FP_INVALID_IMPL = FP_X_INV + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + fp_rnd _rnd; + fp_except _exc; +}; + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_SUN_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_WIN32.h new file mode 100644 index 0000000000..1d6bbb0181 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FPEnvironment_WIN32.h @@ -0,0 +1,158 @@ +// +// FPEnvironment_WIN32.h +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FPEnvironment_WIN32_INCLUDED +#define Foundation_FPEnvironment_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include <float.h> +#include <math.h> + +#ifndef _SW_INEXACT +# define _SW_INEXACT 0x00000001 // inexact (precision) +#endif +#ifndef _SW_UNDERFLOW +# define _SW_UNDERFLOW 0x00000002 // underflow +#endif +#ifndef _SW_OVERFLOW +# define _SW_OVERFLOW 0x00000004 // overflow +#endif +#ifndef _SW_ZERODIVIDE +# define _SW_ZERODIVIDE 0x00000008 // zero divide +#endif +#ifndef _SW_INVALID +# define _SW_INVALID 0x00000010 // invalid +#endif +#ifndef _SW_DENORMAL +# define _SW_DENORMAL 0x00080000 // denormal status bit +#endif + + +namespace Poco { + + +class Foundation_API FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = _RC_DOWN, + FP_ROUND_UPWARD_IMPL = _RC_UP, + FP_ROUND_TONEAREST_IMPL = _RC_NEAR, + FP_ROUND_TOWARDZERO_IMPL = _RC_CHOP + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL = _SW_ZERODIVIDE, + FP_INEXACT_IMPL = _SW_INEXACT, + FP_OVERFLOW_IMPL = _SW_OVERFLOW, + FP_UNDERFLOW_IMPL = _SW_UNDERFLOW, + FP_INVALID_IMPL = _SW_INVALID + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + unsigned _env; +}; + + +// +// inlines +// +inline bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + return _finite(value) == 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + return _finite(value) == 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ +#ifdef __MINGW32__ + return isfinite(value) == 0; +#else + return _finite(static_cast<double>(value)) == 0; +#endif +} + + +inline bool FPEnvironmentImpl::isNaNImpl(float value) +{ + return _isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(double value) +{ + return _isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(long double value) +{ +#ifdef __MINGW32__ + return isnan(value) != 0; +#else + return _isnan(static_cast<double>(value)) != 0; +#endif +} + + +inline float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + return float(_copysign(target, source)); +} + + +inline double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + return _copysign(target, source); +} + + +inline long double FPEnvironmentImpl::copySignImpl(long double target, long double source) +{ + return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target; +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/File.h b/contrib/libs/poco/Foundation/include/Poco/File.h new file mode 100644 index 0000000000..afecf32126 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/File.h @@ -0,0 +1,315 @@ +// +// File.h +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the File class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_File_INCLUDED +#define Foundation_File_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include <vector> + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#if defined(_WIN32_WCE) +#include "File_WINCE.h" +#else +#include "Poco/File_WIN32U.h" +#endif +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/File_WIN32.h" +#elif defined(POCO_VXWORKS) +#include "Poco/File_VX.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/File_UNIX.h" +#endif + + +namespace Poco { + + +class Path; + + +class Foundation_API File: private FileImpl + /// The File class provides methods for working with a file. + /// + /// Regarding paths passed to the various methods, note that + /// platform-specific limitations regarding maximum length + /// of the entire path and its components apply. + /// + /// On Windows, if compiled with UTF-8 support (POCO_WIN32_UTF8) + /// the implementation tries to work around the rather low + /// 260 characters MAX_PATH limit by adding the "\\?\" prefix if + /// a path is absolute and exceeds MAX_PATH characters in length. + /// Note that various limitations regarding usage of the "\\?\" + /// prefix apply in that case, e.g. the path must + /// not contain relative components ("." and "..") and must not + /// use the forward slash ("/") as directory separator. +{ +public: + typedef FileSizeImpl FileSize; + + enum LinkType + /// Type of link for linkTo(). + { + LINK_HARD = 0, /// hard link + LINK_SYMBOLIC = 1 /// symbolic link + }; + + File(); + /// Creates the file. + + File(const std::string& path); + /// Creates the file. + + File(const char* path); + /// Creates the file. + + File(const Path& path); + /// Creates the file. + + File(const File& file); + /// Copy constructor. + + virtual ~File(); + /// Destroys the file. + + File& operator = (const File& file); + /// Assignment operator. + + File& operator = (const std::string& path); + /// Assignment operator. + + File& operator = (const char* path); + /// Assignment operator. + + File& operator = (const Path& path); + /// Assignment operator. + + void swap(File& file); + /// Swaps the file with another one. + + const std::string& path() const; + /// Returns the path. + + bool exists() const; + /// Returns true iff the file exists. + + bool canRead() const; + /// Returns true iff the file is readable. + + bool canWrite() const; + /// Returns true iff the file is writeable. + + bool canExecute() const; + /// Returns true iff the file is executable. + /// + /// On Windows, the file must have + /// the extension ".EXE" to be executable. + /// On Unix platforms, the executable permission + /// bit must be set. + + bool isFile() const; + /// Returns true iff the file is a regular file. + + bool isLink() const; + /// Returns true iff the file is a symbolic link. + + bool isDirectory() const; + /// Returns true iff the file is a directory. + + bool isDevice() const; + /// Returns true iff the file is a device. + + bool isHidden() const; + /// Returns true if the file is hidden. + /// + /// On Windows platforms, the file's hidden + /// attribute is set for this to be true. + /// + /// On Unix platforms, the file name must + /// begin with a period for this to be true. + + Timestamp created() const; + /// Returns the creation date of the file. + /// + /// Not all platforms or filesystems (e.g. Linux and most Unix + /// platforms with the exception of FreeBSD and Mac OS X) + /// maintain the creation date of a file. + /// On such platforms, created() returns + /// the time of the last inode modification. + + Timestamp getLastModified() const; + /// Returns the modification date of the file. + + File& setLastModified(const Timestamp& ts); + /// Sets the modification date of the file. + + FileSize getSize() const; + /// Returns the size of the file in bytes. + + File& setSize(FileSize size); + /// Sets the size of the file in bytes. Can be used + /// to truncate a file. + + File& setWriteable(bool flag = true); + /// Makes the file writeable (if flag is true), or + /// non-writeable (if flag is false) by setting the + /// file's flags in the filesystem accordingly. + + File& setReadOnly(bool flag = true); + /// Makes the file non-writeable (if flag is true), or + /// writeable (if flag is false) by setting the + /// file's flags in the filesystem accordingly. + + File& setExecutable(bool flag = true); + /// Makes the file executable (if flag is true), or + /// non-executable (if flag is false) by setting + /// the file's permission bits accordingly. + /// + /// Does nothing on Windows. + + void copyTo(const std::string& path) const; + /// Copies the file (or directory) to the given path. + /// The target path can be a directory. + /// + /// A directory is copied recursively. + + void moveTo(const std::string& path); + /// Copies the file (or directory) to the given path and + /// removes the original file. The target path can be a directory. + + void renameTo(const std::string& path); + /// Renames the file to the new name. + + void linkTo(const std::string& path, LinkType type = LINK_SYMBOLIC) const; + /// Creates a link (symbolic or hard, depending on type argument) + /// at the given path to the file or directory. + /// + /// May not be supported on all platforms. + /// Furthermore, some operating systems do not allow creating + /// hard links to directories. + + void remove(bool recursive = false); + /// Deletes the file. If recursive is true and the + /// file is a directory, recursively deletes all + /// files in the directory. + + bool createFile(); + /// Creates a new, empty file in an atomic operation. + /// Returns true if the file has been created and false + /// if the file already exists. Throws an exception if + /// an error occurs. + + bool createDirectory(); + /// Creates a directory. Returns true if the directory + /// has been created and false if it already exists. + /// Throws an exception if an error occurs. + + void createDirectories(); + /// Creates a directory (and all parent directories + /// if necessary). + + void list(std::vector<std::string>& files) const; + /// Fills the vector with the names of all + /// files in the directory. + + void list(std::vector<File>& files) const; + /// Fills the vector with the names of all + /// files in the directory. + + FileSize totalSpace() const; + /// Returns the total size in bytes of the partition containing this path. + + FileSize usableSpace() const; + /// Returns the number of usable free bytes on the partition containing this path. + + FileSize freeSpace() const; + /// Returns the number of free bytes on the partition containing this path. + + bool operator == (const File& file) const; + bool operator != (const File& file) const; + bool operator < (const File& file) const; + bool operator <= (const File& file) const; + bool operator > (const File& file) const; + bool operator >= (const File& file) const; + + static void handleLastError(const std::string& path); + /// For internal use only. Throws an appropriate + /// exception for the last file-related error. + +protected: + void copyDirectory(const std::string& path) const; + /// Copies a directory. Used internally by copyTo(). +}; + + +// +// inlines +// +inline const std::string& File::path() const +{ + return getPathImpl(); +} + + +inline bool File::operator == (const File& file) const +{ + return getPathImpl() == file.getPathImpl(); +} + + +inline bool File::operator != (const File& file) const +{ + return getPathImpl() != file.getPathImpl(); +} + + +inline bool File::operator < (const File& file) const +{ + return getPathImpl() < file.getPathImpl(); +} + + +inline bool File::operator <= (const File& file) const +{ + return getPathImpl() <= file.getPathImpl(); +} + + +inline bool File::operator > (const File& file) const +{ + return getPathImpl() > file.getPathImpl(); +} + + +inline bool File::operator >= (const File& file) const +{ + return getPathImpl() >= file.getPathImpl(); +} + + +inline void swap(File& f1, File& f2) +{ + f1.swap(f2); +} + + +} // namespace Poco + + +#endif // Foundation_File_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FileChannel.h b/contrib/libs/poco/Foundation/include/Poco/FileChannel.h new file mode 100644 index 0000000000..a7b421b3d2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FileChannel.h @@ -0,0 +1,271 @@ +// +// FileChannel.h +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Definition of the FileChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FileChannel_INCLUDED +#define Foundation_FileChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class LogFile; +class RotateStrategy; +class ArchiveStrategy; +class PurgeStrategy; + + +class Foundation_API FileChannel: public Channel + /// A Channel that writes to a file. This class supports + /// flexible log file rotation and archiving, as well + /// as automatic purging of archived log files. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is in the text. + /// + /// The FileChannel support log file rotation based + /// on log file size or time intervals. + /// Archived log files can be compressed in gzip format. + /// Older archived files can be automatically deleted + /// (purged). + /// + /// The rotation strategy can be specified with the + /// "rotation" property, which can take one of the + /// follwing values: + /// + /// * never: no log rotation + /// * [day,][hh]:mm: the file is rotated on specified day/time + /// day - day is specified as long or short day name (Monday|Mon, Tuesday|Tue, ... ); + /// day can be omitted, in which case log is rotated every day + /// hh - valid hour range is 00-23; + /// hour can be omitted, in which case log is rotated every hour + /// mm - valid minute range is 00-59; + /// minute must be specified + /// * daily: the file is rotated daily + /// * weekly: the file is rotated every seven days + /// * monthly: the file is rotated every 30 days + /// * <n> minutes: the file is rotated every <n> minutes, + /// where <n> is an integer greater than zero. + /// * <n> hours: the file is rotated every <n> hours, where + /// <n> is an integer greater than zero. + /// * <n> days: the file is rotated every <n> days, where + /// <n> is an integer greater than zero. + /// * <n> weeks: the file is rotated every <n> weeks, where + /// <n> is an integer greater than zero. + /// * <n> months: the file is rotated every <n> months, where + /// <n> is an integer greater than zero and + /// a month has 30 days. + /// * <n>: the file is rotated when its size exceeds + /// <n> bytes. + /// * <n> K: the file is rotated when its size exceeds + /// <n> Kilobytes. + /// * <n> M: the file is rotated when its size exceeds + /// <n> Megabytes. + /// + /// NOTE: For periodic log file rotation (daily, weekly, monthly, etc.), + /// the date and time of log file creation or last rotation is + /// written into the first line of the log file. This is because + /// there is no reliable way to find out the real creation date of + /// a file on many platforms (e.g., most Unix platforms do not + /// provide the creation date, and Windows has its own issues + /// with its "File System Tunneling Capabilities"). + /// + /// Using the "archive" property it is possible to specify + /// how archived log files are named. The following values + /// for the "archive" property are supported: + /// + /// * number: A number, starting with 0, is appended to + /// the name of archived log files. The newest + /// archived log file always has the number 0. + /// For example, if the log file is named + /// "access.log", and it fulfils the criteria + /// for rotation, the file is renamed to + /// "access.log.0". If a file named "access.log.0" + /// already exists, it is renamed to "access.log.1", + /// and so on. + /// * timestamp: A timestamp is appended to the log file name. + /// For example, if the log file is named + /// "access.log", and it fulfils the criteria + /// for rotation, the file is renamed to + /// "access.log.20050802110300". + /// + /// Using the "times" property it is possible to specify + /// time mode for the day/time based rotation. The following values + /// for the "times" property are supported: + /// + /// * utc: Rotation strategy is based on UTC time (default). + /// * local: Rotation strategy is based on local time. + /// + /// Archived log files can be compressed using the gzip compression + /// method. Compressing can be controlled with the "compress" + /// property. The following values for the "compress" property + /// are supported: + /// + /// * true: Compress archived log files. + /// * false: Do not compress archived log files. + /// + /// Archived log files can be automatically purged, either if + /// they reach a certain age, or if the number of archived + /// log files reaches a given maximum number. This is + /// controlled by the purgeAge and purgeCount properties. + /// + /// The purgeAge property can have the following values: + /// + /// * <n> [seconds]: the maximum age is <n> seconds. + /// * <n> minutes: the maximum age is <n> minutes. + /// * <n> hours: the maximum age is <n> hours. + /// * <n> days: the maximum age is <n> days. + /// * <n> weeks: the maximum age is <n> weeks. + /// * <n> months: the maximum age is <n> months, where a month has 30 days. + /// + /// The purgeCount property has an integer value that specifies the maximum number + /// of archived log files. If the number is exceeded, archived log files are + /// deleted, starting with the oldest. When "none" or empty string are + /// supplied, they reset purgeCount to none (no purging). + /// + /// The flush property specifies whether each log message is flushed + /// immediately to the log file (which may hurt application performance, + /// but ensures that everything is in the log in case of a system crash), + // or whether it's allowed to stay in the system's file buffer for some time. + /// Valid values are: + /// + /// * true: Every essages is immediately flushed to the log file (default). + /// * false: Messages are not immediately flushed to the log file. + /// + /// The rotateOnOpen property specifies whether an existing log file should be + /// rotated (and archived) when the channel is opened. Valid values are: + /// + /// * true: The log file is rotated (and archived) when the channel is opened. + /// * false: Log messages will be appended to an existing log file, + /// if it exists (unless other conditions for a rotation are met). + /// This is the default. + /// + /// For a more lightweight file channel class, see SimpleFileChannel. +{ +public: + FileChannel(); + /// Creates the FileChannel. + + FileChannel(const std::string& path); + /// Creates the FileChannel for a file with the given path. + + void open(); + /// Opens the FileChannel and creates the log file if necessary. + + void close(); + /// Closes the FileChannel. + + void log(const Message& msg); + /// Logs the given message to the file. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name. + /// + /// The following properties are supported: + /// * path: The log file's path. + /// * rotation: The log file's rotation mode. See the + /// FileChannel class for details. + /// * archive: The log file's archive mode. See the + /// FileChannel class for details. + /// * times: The log file's time mode. See the + /// FileChannel class for details. + /// * compress: Enable or disable compression of + /// archived files. See the FileChannel class + /// for details. + /// * purgeAge: Maximum age of an archived log file before + /// it is purged. See the FileChannel class for + /// details. + /// * purgeCount: Maximum number of archived log files before + /// files are purged. See the FileChannel class + /// for details. + /// * flush: Specifies whether messages are immediately + /// flushed to the log file. See the FileChannel class + /// for details. + /// * rotateOnOpen: Specifies whether an existing log file should be + /// rotated and archived when the channel is opened. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + /// See setProperty() for a description of the supported + /// properties. + + Timestamp creationDate() const; + /// Returns the log file's creation date. + + UInt64 size() const; + /// Returns the log file's current size in bytes. + + const std::string& path() const; + /// Returns the log file's path. + + static const std::string PROP_PATH; + static const std::string PROP_ROTATION; + static const std::string PROP_ARCHIVE; + static const std::string PROP_TIMES; + static const std::string PROP_COMPRESS; + static const std::string PROP_PURGEAGE; + static const std::string PROP_PURGECOUNT; + static const std::string PROP_FLUSH; + static const std::string PROP_ROTATEONOPEN; + +protected: + ~FileChannel(); + void setRotation(const std::string& rotation); + void setArchive(const std::string& archive); + void setCompress(const std::string& compress); + void setPurgeAge(const std::string& age); + void setPurgeCount(const std::string& count); + void setFlush(const std::string& flush); + void setRotateOnOpen(const std::string& rotateOnOpen); + void purge(); + void unsafeOpen(); + +private: + bool setNoPurge(const std::string& value); + int extractDigit(const std::string& value, std::string::const_iterator* nextToDigit = NULL) const; + void setPurgeStrategy(PurgeStrategy* strategy); + Timespan::TimeDiff extractFactor(const std::string& value, std::string::const_iterator start) const; + + std::string _path; + std::string _times; + std::string _rotation; + std::string _archive; + bool _compress; + std::string _purgeAge; + std::string _purgeCount; + bool _flush; + bool _rotateOnOpen; + LogFile* _pFile; + RotateStrategy* _pRotateStrategy; + ArchiveStrategy* _pArchiveStrategy; + PurgeStrategy* _pPurgeStrategy; + FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_FileChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FileStream.h b/contrib/libs/poco/Foundation/include/Poco/FileStream.h new file mode 100644 index 0000000000..cea56c9476 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FileStream.h @@ -0,0 +1,176 @@ +// +// FileStream.h +// +// Library: Foundation +// Package: Streams +// Module: FileStream +// +// Definition of the FileStreamBuf, FileInputStream and FileOutputStream classes. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FileStream_INCLUDED +#define Foundation_FileStream_INCLUDED + + +#include "Poco/Foundation.h" +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/FileStream_WIN32.h" +#else +#include "Poco/FileStream_POSIX.h" +#endif +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API FileIOS: public virtual std::ios + /// The base class for FileInputStream and FileOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. + /// + /// Files are always opened in binary mode, a text mode + /// with CR-LF translation is not supported. Thus, the + /// file is always opened as if the std::ios::binary flag + /// was specified. + /// Use an InputLineEndingConverter or OutputLineEndingConverter + /// if you require CR-LF translation. + /// + /// On Windows platforms, if POCO_WIN32_UTF8 is #define'd, + /// UTF-8 encoded Unicode paths are correctly handled. +{ +public: + FileIOS(std::ios::openmode defaultMode); + /// Creates the basic stream. + + ~FileIOS(); + /// Destroys the stream. + + void open(const std::string& path, std::ios::openmode mode); + /// Opens the file specified by path, using the given mode. + /// + /// Throws a FileException (or a similar exception) if the file + /// does not exist or is not accessible for other reasons and + /// a new file cannot be created. + + void close(); + /// Closes the file stream. + /// + /// If, for an output stream, the close operation fails (because + /// the contents of the stream buffer cannot synced back to + /// the filesystem), the bad bit is set in the stream state. + + FileStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + FileStreamBuf _buf; + std::ios::openmode _defaultMode; +}; + + +class Foundation_API FileInputStream: public FileIOS, public std::istream + /// An input stream for reading from a file. + /// + /// Files are always opened in binary mode, a text mode + /// with CR-LF translation is not supported. Thus, the + /// file is always opened as if the std::ios::binary flag + /// was specified. + /// Use an InputLineEndingConverter if you require CR-LF translation. + /// + /// On Windows platforms, if POCO_WIN32_UTF8 is #define'd, + /// UTF-8 encoded Unicode paths are correctly handled. +{ +public: + FileInputStream(); + /// Creates an unopened FileInputStream. + + FileInputStream(const std::string& path, std::ios::openmode mode = std::ios::in); + /// Creates the FileInputStream for the file given by path, using + /// the given mode. + /// + /// The std::ios::in flag is always set, regardless of the actual + /// value specified for mode. + /// + /// Throws a FileNotFoundException (or a similar exception) if the file + /// does not exist or is not accessible for other reasons. + + ~FileInputStream(); + /// Destroys the stream. +}; + + +class Foundation_API FileOutputStream: public FileIOS, public std::ostream + /// An output stream for writing to a file. + /// + /// Files are always opened in binary mode, a text mode + /// with CR-LF translation is not supported. Thus, the + /// file is always opened as if the std::ios::binary flag + /// was specified. + /// Use an OutputLineEndingConverter if you require CR-LF translation. + /// + /// On Windows platforms, if POCO_WIN32_UTF8 is #define'd, + /// UTF-8 encoded Unicode paths are correctly handled. +{ +public: + FileOutputStream(); + /// Creats an unopened FileOutputStream. + + FileOutputStream(const std::string& path, std::ios::openmode mode = std::ios::out | std::ios::trunc); + /// Creates the FileOutputStream for the file given by path, using + /// the given mode. + /// + /// The std::ios::out is always set, regardless of the actual + /// value specified for mode. + /// + /// Throws a FileException (or a similar exception) if the file + /// does not exist or is not accessible for other reasons and + /// a new file cannot be created. + + ~FileOutputStream(); + /// Destroys the FileOutputStream. +}; + + +class Foundation_API FileStream: public FileIOS, public std::iostream + /// A stream for reading from and writing to a file. + /// + /// Files are always opened in binary mode, a text mode + /// with CR-LF translation is not supported. Thus, the + /// file is always opened as if the std::ios::binary flag + /// was specified. + /// Use an InputLineEndingConverter or OutputLineEndingConverter + /// if you require CR-LF translation. + /// + /// A seek (seekg() or seekp()) operation will always set the + /// read position and the write position simultaneously to the + /// same value. + /// + /// On Windows platforms, if POCO_WIN32_UTF8 is #define'd, + /// UTF-8 encoded Unicode paths are correctly handled. +{ +public: + FileStream(); + /// Creats an unopened FileStream. + + FileStream(const std::string& path, std::ios::openmode mode = std::ios::out | std::ios::in); + /// Creates the FileStream for the file given by path, using + /// the given mode. + + ~FileStream(); + /// Destroys the FileOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_FileStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FileStreamFactory.h b/contrib/libs/poco/Foundation/include/Poco/FileStreamFactory.h new file mode 100644 index 0000000000..01364cf1da --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FileStreamFactory.h @@ -0,0 +1,61 @@ +// +// FileStreamFactory.h +// +// Library: Foundation +// Package: URI +// Module: FileStreamFactory +// +// Definition of the FileStreamFactory class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FileStreamFactory_INCLUDED +#define Foundation_FileStreamFactory_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/URIStreamFactory.h" + + +namespace Poco { + + +class Path; + + +class Foundation_API FileStreamFactory: public URIStreamFactory + /// An implementation of the URIStreamFactory interface + /// that handles file URIs. +{ +public: + FileStreamFactory(); + /// Creates the FileStreamFactory. + + ~FileStreamFactory(); + /// Destroys the FileStreamFactory. + + std::istream* open(const URI& uri); + /// Creates and opens a file stream in binary mode for the given URI. + /// The URI must be either a file URI or a relative URI reference + /// containing a path to a local file. + /// + /// Throws an FileNotFound exception if the file cannot + /// be opened. + + std::istream* open(const Path& path); + /// Creates and opens a file stream in binary mode for the given path. + /// + /// Throws an FileNotFound exception if the file cannot + /// be opened. +}; + + +} // namespace Poco + + +#endif // Foundation_FileStreamFactory_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FileStream_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/FileStream_POSIX.h new file mode 100644 index 0000000000..f5fa25cb8a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FileStream_POSIX.h @@ -0,0 +1,72 @@ +// +// FileStream_POSIX.h +// +// Library: Foundation +// Package: Streams +// Module: FileStream +// +// Definition of the FileStreamBuf, FileInputStream and FileOutputStream classes. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FileStream_POSIX_INCLUDED +#define Foundation_FileStream_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedBidirectionalStreamBuf.h" +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API FileStreamBuf: public BufferedBidirectionalStreamBuf + /// This stream buffer handles Fileio +{ +public: + FileStreamBuf(); + /// Creates a FileStreamBuf. + + ~FileStreamBuf(); + /// Destroys the FileStream. + + void open(const std::string& path, std::ios::openmode mode); + /// Opens the given file in the given mode. + + bool close(); + /// Closes the File stream buffer. Returns true if successful, + /// false otherwise. + + std::streampos seekoff(std::streamoff off, std::ios::seekdir dir, std::ios::openmode mode = std::ios::in | std::ios::out); + /// Change position by offset, according to way and mode. + + std::streampos seekpos(std::streampos pos, std::ios::openmode mode = std::ios::in | std::ios::out); + /// Change to specified position, according to mode. + +protected: + enum + { + BUFFER_SIZE = 4096 + }; + + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + std::string _path; + int _fd; + std::streamoff _pos; +}; + + +} // namespace Poco + + +#endif // Foundation_FileStream_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FileStream_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/FileStream_WIN32.h new file mode 100644 index 0000000000..5382f84db3 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FileStream_WIN32.h @@ -0,0 +1,71 @@ +// +// FileStream_WIN32.h +// +// Library: Foundation +// Package: Streams +// Module: FileStream +// +// Definition of the FileStreamBuf, FileInputStream and FileOutputStream classes. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FileStream_WIN32_INCLUDED +#define Foundation_FileStream_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedBidirectionalStreamBuf.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API FileStreamBuf: public BufferedBidirectionalStreamBuf + /// This stream buffer handles Fileio +{ +public: + FileStreamBuf(); + /// Creates a FileStreamBuf. + + ~FileStreamBuf(); + /// Destroys the FileStream. + + void open(const std::string& path, std::ios::openmode mode); + /// Opens the given file in the given mode. + + bool close(); + /// Closes the File stream buffer. Returns true if successful, + /// false otherwise. + + std::streampos seekoff(std::streamoff off, std::ios::seekdir dir, std::ios::openmode mode = std::ios::in | std::ios::out); + /// change position by offset, according to way and mode + + std::streampos seekpos(std::streampos pos, std::ios::openmode mode = std::ios::in | std::ios::out); + /// change to specified position, according to mode + +protected: + enum + { + BUFFER_SIZE = 4096 + }; + + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + std::string _path; + HANDLE _handle; + UInt64 _pos; +}; + + +} // namespace Poco + + +#endif // Foundation_FileStream_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/File_UNIX.h b/contrib/libs/poco/Foundation/include/Poco/File_UNIX.h new file mode 100644 index 0000000000..34a15c573d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/File_UNIX.h @@ -0,0 +1,86 @@ +// +// File_UNIX.h +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the FileImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_File_UNIX_INCLUDED +#define Foundation_File_UNIX_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool canExecuteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + bool isDeviceImpl() const; + bool isHiddenImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void setExecutableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void linkToImpl(const std::string& path, int type) const; + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + FileSizeImpl totalSpaceImpl() const; + FileSizeImpl usableSpaceImpl() const; + FileSizeImpl freeSpaceImpl() const; + static void handleLastErrorImpl(const std::string& path); + +private: + std::string _path; + + friend class DirectoryIteratorImpl; + friend class LinuxDirectoryWatcherStrategy; + friend class BSDDirectoryWatcherStrategy; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/File_VX.h b/contrib/libs/poco/Foundation/include/Poco/File_VX.h new file mode 100644 index 0000000000..3d66f96647 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/File_VX.h @@ -0,0 +1,84 @@ +// +// File_VX.h +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the FileImpl class for VxWorks. +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_File_VX_INCLUDED +#define Foundation_File_VX_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool canExecuteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + bool isDeviceImpl() const; + bool isHiddenImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void setExecutableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void linkToImpl(const std::string& path, int type) const; + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + FileSizeImpl totalSpaceImpl() const; + FileSizeImpl usableSpaceImpl() const; + FileSizeImpl freeSpaceImpl() const; + static void handleLastErrorImpl(const std::string& path); + +private: + std::string _path; + + friend class DirectoryIteratorImpl; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/File_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/File_WIN32.h new file mode 100644 index 0000000000..2d8b888074 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/File_WIN32.h @@ -0,0 +1,87 @@ +// +// File_WIN32.h +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the FileImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_File_WIN32_INCLUDED +#define Foundation_File_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool canExecuteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + bool isDeviceImpl() const; + bool isHiddenImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void setExecutableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void linkToImpl(const std::string& path, int type) const; + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + FileSizeImpl totalSpaceImpl() const; + FileSizeImpl usableSpaceImpl() const; + FileSizeImpl freeSpaceImpl() const; + static void handleLastErrorImpl(const std::string& path); + +private: + std::string _path; + + friend class FileHandle; + friend class DirectoryIteratorImpl; + friend class WindowsDirectoryWatcherStrategy; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/File_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/File_WIN32U.h new file mode 100644 index 0000000000..835da87a15 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/File_WIN32U.h @@ -0,0 +1,91 @@ +// +// File_WIN32U.h +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the Unicode FileImpl class for WIN32. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_File_WIN32U_INCLUDED +#define Foundation_File_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool canExecuteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + bool isDeviceImpl() const; + bool isHiddenImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void setExecutableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void linkToImpl(const std::string& path, int type) const; + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + FileSizeImpl totalSpaceImpl() const; + FileSizeImpl usableSpaceImpl() const; + FileSizeImpl freeSpaceImpl() const; + static void handleLastErrorImpl(const std::string& path); + static void convertPath(const std::string& utf8Path, std::wstring& utf16Path); + +private: + std::string _path; + std::wstring _upath; + + friend class FileHandle; + friend class DirectoryIteratorImpl; + friend class WindowsDirectoryWatcherStrategy; + friend class FileStreamBuf; + friend class LogFileImpl; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/File_WINCE.h b/contrib/libs/poco/Foundation/include/Poco/File_WINCE.h new file mode 100644 index 0000000000..c1ba4f3507 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/File_WINCE.h @@ -0,0 +1,90 @@ +// +// File_WIN32U.h +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the Unicode FileImpl class for WIN32. +// +// Copyright (c) 2006-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_File_WINCE_INCLUDED +#define Foundation_File_WINCE_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool canExecuteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + bool isDeviceImpl() const; + bool isHiddenImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void setExecutableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void linkToImpl(const std::string& path, int type) const; + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + FileSizeImpl totalSpaceImpl() const; + FileSizeImpl usableSpaceImpl() const; + FileSizeImpl freeSpaceImpl() const; + static void handleLastErrorImpl(const std::string& path); + static void convertPath(const std::string& utf8Path, std::wstring& utf16Path); + +private: + std::string _path; + std::wstring _upath; + + friend class FileHandle; + friend class DirectoryIteratorImpl; + friend class FileStreamBuf; + friend class LogFileImpl; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_WINCE_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Format.h b/contrib/libs/poco/Foundation/include/Poco/Format.h new file mode 100644 index 0000000000..e4b093a407 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Format.h @@ -0,0 +1,138 @@ +// +// Format.h +// +// Library: Foundation +// Package: Core +// Module: Format +// +// Definition of the format freestanding function. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Format_INCLUDED +#define Foundation_Format_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Any.h" +#include <vector> + + +namespace Poco { + + +std::string Foundation_API format(const std::string& fmt, const Any& value); + /// This function implements sprintf-style formatting in a typesafe way. + /// Various variants of the function are available, supporting a + /// different number of arguments (up to six). + /// + /// The formatting is controlled by the format string in fmt. + /// Format strings are quite similar to those of the std::printf() function, but + /// there are some minor differences. + /// + /// The format string can consist of any sequence of characters; certain + /// characters have a special meaning. Characters without a special meaning + /// are copied verbatim to the result. A percent sign (%) marks the beginning + /// of a format specification. Format specifications have the following syntax: + /// + /// %[<index>][<flags>][<width>][.<precision>][<modifier>]<type> + /// + /// Index, flags, width, precision and prefix are optional. The only required part of + /// the format specification, apart from the percent sign, is the type. + /// + /// The optional index argument has the format "[<n>]" and allows to + /// address an argument by its zero-based position (see the example below). + /// + /// Following are valid type specifications and their meaning: + /// + /// * b boolean (true = 1, false = 0) + /// * c character + /// * d signed decimal integer + /// * i signed decimal integer + /// * o unsigned octal integer + /// * u unsigned decimal integer + /// * x unsigned hexadecimal integer (lower case) + /// * X unsigned hexadecimal integer (upper case) + /// * e signed floating-point value in the form [-]d.dddde[<sign>]dd[d] + /// * E signed floating-point value in the form [-]d.ddddE[<sign>]dd[d] + /// * f signed floating-point value in the form [-]dddd.dddd + /// * s std::string + /// * z std::size_t + /// + /// The following flags are supported: + /// + /// * - left align the result within the given field width + /// * + prefix the output value with a sign (+ or -) if the output value is of a signed type + /// * 0 if width is prefixed with 0, zeros are added until the minimum width is reached + /// * # For o, x, X, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively; + /// for e, E, f, the # flag forces the output value to contain a decimal point in all cases. + /// + /// The following modifiers are supported: + /// + /// * (none) argument is char (c), int (d, i), unsigned (o, u, x, X) double (e, E, f, g, G) or string (s) + /// * l argument is long (d, i), unsigned long (o, u, x, X) or long double (e, E, f, g, G) + /// * L argument is long long (d, i), unsigned long long (o, u, x, X) + /// * h argument is short (d, i), unsigned short (o, u, x, X) or float (e, E, f, g, G) + /// * ? argument is any signed or unsigned int, short, long, or 64-bit integer (d, i, o, x, X) + /// + /// The width argument is a nonnegative decimal integer controlling the minimum number of characters printed. + /// If the number of characters in the output value is less than the specified width, blanks or + /// leading zeros are added, according to the specified flags (-, +, 0). + /// + /// Precision is a nonnegative decimal integer, preceded by a period (.), which specifies the number of characters + /// to be printed, the number of decimal places, or the number of significant digits. + /// + /// Throws an InvalidArgumentException if an argument index is out of range. + /// + /// Starting with release 1.4.3, an argument that does not match the format + /// specifier no longer results in a BadCastException. The string [ERRFMT] is + /// written to the result string instead. + /// + /// If there are more format specifiers than values, the format specifiers without a corresponding value + /// are copied verbatim to output. + /// + /// If there are more values than format specifiers, the superfluous values are ignored. + /// + /// Usage Examples: + /// std::string s1 = format("The answer to life, the universe, and everything is %d", 42); + /// std::string s2 = format("second: %[1]d, first: %[0]d", 1, 2); + +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value); + /// Appends the formatted string to result. + +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + +void Foundation_API format(std::string& result, const std::string& fmt, const std::vector<Any>& values); + /// Supports a variable number of arguments and is used by + /// all other variants of format(). + + +} // namespace Poco + + +#endif // Foundation_Format_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Formatter.h b/contrib/libs/poco/Foundation/include/Poco/Formatter.h new file mode 100644 index 0000000000..678d594b72 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Formatter.h @@ -0,0 +1,74 @@ +// +// Formatter.h +// +// Library: Foundation +// Package: Logging +// Module: Formatter +// +// Definition of the Formatter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Formatter_INCLUDED +#define Foundation_Formatter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Configurable.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Message; + + +class Foundation_API Formatter: public Configurable, public RefCountedObject + /// The base class for all Formatter classes. + /// + /// A formatter basically takes a Message object + /// and formats it into a string. How the formatting + /// is exactly done is up to the implementation of + /// Formatter. For example, a very simple implementation + /// might simply take the message's Text (see Message::getText()). + /// A useful implementation should at least take the Message's + /// Time, Priority and Text fields and put them into a string. + /// + /// The Formatter class supports the Configurable + /// interface, so the behaviour of certain formatters + /// is configurable. + /// + /// Trivial implementations of of getProperty() and + /// setProperty() are provided. + /// + /// Subclasses must at least provide a format() method. +{ +public: + Formatter(); + /// Creates the formatter. + + virtual ~Formatter(); + /// Destroys the formatter. + + virtual void format(const Message& msg, std::string& text) = 0; + /// Formats the message and places the result in text. + /// Subclasses must override this method. + + void setProperty(const std::string& name, const std::string& value); + /// Throws a PropertyNotSupportedException. + + std::string getProperty(const std::string& name) const; + /// Throws a PropertyNotSupportedException. +}; + + +} // namespace Poco + + +#endif // Foundation_Formatter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FormattingChannel.h b/contrib/libs/poco/Foundation/include/Poco/FormattingChannel.h new file mode 100644 index 0000000000..f4dfded2a7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FormattingChannel.h @@ -0,0 +1,96 @@ +// +// FormattingChannel.h +// +// Library: Foundation +// Package: Logging +// Module: Formatter +// +// Definition of the FormattingChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FormattingChannel_INCLUDED +#define Foundation_FormattingChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" + + +namespace Poco { + + +class Formatter; + + +class Foundation_API FormattingChannel: public Channel + /// The FormattingChannel is a filter channel that routes + /// a Message through a Formatter before passing it on + /// to the destination channel. +{ +public: + FormattingChannel(); + /// Creates a FormattingChannel. + + FormattingChannel(Formatter* pFormatter); + /// Creates a FormattingChannel and attaches a Formatter. + + FormattingChannel(Formatter* pFormatter, Channel* pChannel); + /// Creates a FormattingChannel and attaches a Formatter + /// and a Channel. + + void setFormatter(Formatter* pFormatter); + /// Sets the Formatter used to format the messages + /// before they are passed on. If null, the message + /// is passed on unmodified. + + Formatter* getFormatter() const; + /// Returns the Formatter used to format messages, + /// which may be null. + + void setChannel(Channel* pChannel); + /// Sets the destination channel to which the formatted + /// messages are passed on. + + Channel* getChannel() const; + /// Returns the channel to which the formatted + /// messages are passed on. + + void log(const Message& msg); + /// Formats the given Message using the Formatter and + /// passes the formatted message on to the destination + /// Channel. + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// Only the "channel" and "formatter" properties are supported, which allow + /// setting the target channel and formatter, respectively, via the LoggingRegistry. + /// The "channel" and "formatter" properties are set-only. + /// + /// Unsupported properties are passed to the attached Channel. + + void open(); + /// Opens the attached channel. + + void close(); + /// Closes the attached channel. + +protected: + ~FormattingChannel(); + +private: + Formatter* _pFormatter; + Channel* _pChannel; +}; + + +} // namespace Poco + + +#endif // Foundation_FormattingChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Foundation.h b/contrib/libs/poco/Foundation/include/Poco/Foundation.h new file mode 100644 index 0000000000..750c7775e7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Foundation.h @@ -0,0 +1,168 @@ +// +// Foundation.h +// +// Library: Foundation +// Package: Core +// Module: Foundation +// +// Basic definitions for the POCO Foundation library. +// This file must be the first file included by every other Foundation +// header file. +// +// Copyright (c) 2004-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Foundation_INCLUDED +#define Foundation_Foundation_INCLUDED + + +// +// Include library configuration +// +#include "Poco/Config.h" + + +// +// Ensure that POCO_DLL is default unless POCO_STATIC is defined +// +#if defined(_WIN32) && defined(_DLL) + #if !defined(POCO_DLL) && !defined(POCO_STATIC) + #define POCO_DLL + #endif +#endif + + +// +// 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 Foundation_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 +// Foundation_API functions as being imported from a DLL, wheras this DLL sees symbols +// defined with this macro as being exported. +// +#if (defined(_WIN32) || defined(_WIN32_WCE)) && defined(POCO_DLL) + #if defined(Foundation_EXPORTS) + #define Foundation_API __declspec(dllexport) + #else + #define Foundation_API __declspec(dllimport) + #endif +#endif + + +#if !defined(Foundation_API) + #if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4) + #define Foundation_API __attribute__ ((visibility ("default"))) + #else + #define Foundation_API + #endif +#endif + + +// +// Automatically link Foundation library. +// +#if defined(_MSC_VER) + #if defined(POCO_DLL) + #if defined(_DEBUG) + #define POCO_LIB_SUFFIX "d.lib" + #else + #define POCO_LIB_SUFFIX ".lib" + #endif + #elif defined(_DLL) + #if defined(_DEBUG) + #define POCO_LIB_SUFFIX "mdd.lib" + #else + #define POCO_LIB_SUFFIX "md.lib" + #endif + #else + #if defined(_DEBUG) + #define POCO_LIB_SUFFIX "mtd.lib" + #else + #define POCO_LIB_SUFFIX "mt.lib" + #endif + #endif + + #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(Foundation_EXPORTS) + #pragma comment(lib, "PocoFoundation" POCO_LIB_SUFFIX) + #endif +#endif + + +// +// Include platform-specific definitions +// +#include "Poco/Platform.h" +#if defined(_WIN32) + #include "Poco/Platform_WIN32.h" +#elif defined(POCO_VXWORKS) + #include "Poco/Platform_VX.h" +#elif defined(POCO_OS_FAMILY_UNIX) + #include "Poco/Platform_POSIX.h" +#endif + + +// +// Include alignment settings early +// +#include "Poco/Alignment.h" + +// +// Cleanup inconsistencies +// +#ifdef POCO_OS_FAMILY_WINDOWS + #if defined(POCO_WIN32_UTF8) && defined(POCO_NO_WSTRING) + #error POCO_WIN32_UTF8 and POCO_NO_WSTRING are mutually exclusive. + #endif +#else + #ifdef POCO_WIN32_UTF8 + #undef POCO_WIN32_UTF8 + #endif +#endif + + +// +// POCO_JOIN +// +// The following piece of macro magic joins the two +// arguments together, even when one of the arguments is +// itself a macro (see 16.3.1 in C++ standard). The key +// is that macro expansion of macro arguments does not +// occur in POCO_DO_JOIN2 but does in POCO_DO_JOIN. +// +#define POCO_JOIN(X, Y) POCO_DO_JOIN(X, Y) +#define POCO_DO_JOIN(X, Y) POCO_DO_JOIN2(X, Y) +#define POCO_DO_JOIN2(X, Y) X##Y + + +// +// POCO_DEPRECATED +// +// A macro expanding to a compiler-specific clause to +// mark a class or function as deprecated. +// +#if defined(POCO_NO_DEPRECATED) +#define POCO_DEPRECATED +#elif defined(_GNUC_) +#define POCO_DEPRECATED __attribute__((deprecated)) +#elif defined(__clang__) +#define POCO_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define POCO_DEPRECATED __declspec(deprecated) +#else +#define POCO_DEPRECATED +#endif + + +// +// Pull in basic definitions +// +#include "Poco/Bugcheck.h" +#include "Poco/Types.h" +#include <string> + + +#endif // Foundation_Foundation_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FunctionDelegate.h b/contrib/libs/poco/Foundation/include/Poco/FunctionDelegate.h new file mode 100644 index 0000000000..9aec96d950 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FunctionDelegate.h @@ -0,0 +1,438 @@ +// +// FunctionDelegate.h +// +// Library: Foundation +// Package: Events +// Module: FunctionDelegate +// +// Implementation of the FunctionDelegate template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FunctionDelegate_INCLUDED +#define Foundation_FunctionDelegate_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractDelegate.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class TArgs, bool hasSender = true, bool senderIsConst = true> +class FunctionDelegate: public AbstractDelegate<TArgs> + /// Wraps a freestanding function or static member function + /// for use as a Delegate. +{ +public: + typedef void (*NotifyFunction)(const void*, TArgs&); + + FunctionDelegate(NotifyFunction function): + _function(function) + { + } + + FunctionDelegate(const FunctionDelegate& delegate): + AbstractDelegate<TArgs>(delegate), + _function(delegate._function) + { + } + + ~FunctionDelegate() + { + } + + FunctionDelegate& operator = (const FunctionDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + } + return *this; + } + + bool notify(const void* sender, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(sender, arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const FunctionDelegate* pOtherDelegate = dynamic_cast<const FunctionDelegate*>(other.unwrap()); + return pOtherDelegate && _function == pOtherDelegate->_function; + } + + AbstractDelegate<TArgs>* clone() const + { + return new FunctionDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionDelegate(); +}; + + +template <class TArgs> +class FunctionDelegate<TArgs, true, false>: public AbstractDelegate<TArgs> +{ +public: + typedef void (*NotifyFunction)(void*, TArgs&); + + FunctionDelegate(NotifyFunction function): + _function(function) + { + } + + FunctionDelegate(const FunctionDelegate& delegate): + AbstractDelegate<TArgs>(delegate), + _function(delegate._function) + { + } + + ~FunctionDelegate() + { + } + + FunctionDelegate& operator = (const FunctionDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + } + return *this; + } + + bool notify(const void* sender, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(const_cast<void*>(sender), arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const FunctionDelegate* pOtherDelegate = dynamic_cast<const FunctionDelegate*>(other.unwrap()); + return pOtherDelegate && _function == pOtherDelegate->_function; + } + + AbstractDelegate<TArgs>* clone() const + { + return new FunctionDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionDelegate(); +}; + + +template <class TArgs, bool senderIsConst> +class FunctionDelegate<TArgs, false, senderIsConst>: public AbstractDelegate<TArgs> +{ +public: + typedef void (*NotifyFunction)(TArgs&); + + FunctionDelegate(NotifyFunction function): + _function(function) + { + } + + FunctionDelegate(const FunctionDelegate& delegate): + AbstractDelegate<TArgs>(delegate), + _function(delegate._function) + { + } + + ~FunctionDelegate() + { + } + + FunctionDelegate& operator = (const FunctionDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + } + return *this; + } + + bool notify(const void* /*sender*/, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const FunctionDelegate* pOtherDelegate = dynamic_cast<const FunctionDelegate*>(other.unwrap()); + return pOtherDelegate && _function == pOtherDelegate->_function; + } + + AbstractDelegate<TArgs>* clone() const + { + return new FunctionDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionDelegate(); +}; + + +template <> +class FunctionDelegate<void, true, true>: public AbstractDelegate<void> + /// Wraps a freestanding function or static member function + /// for use as a Delegate. +{ +public: + typedef void (*NotifyFunction)(const void*); + + FunctionDelegate(NotifyFunction function): + _function(function) + { + } + + FunctionDelegate(const FunctionDelegate& delegate): + AbstractDelegate<void>(delegate), + _function(delegate._function) + { + } + + ~FunctionDelegate() + { + } + + FunctionDelegate& operator = (const FunctionDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + } + return *this; + } + + bool notify(const void* sender) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(sender); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const FunctionDelegate* pOtherDelegate = dynamic_cast<const FunctionDelegate*>(other.unwrap()); + return pOtherDelegate && _function == pOtherDelegate->_function; + } + + AbstractDelegate<void>* clone() const + { + return new FunctionDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionDelegate(); +}; + + +template <> +class FunctionDelegate<void, true, false>: public AbstractDelegate<void> +{ +public: + typedef void (*NotifyFunction)(void*); + + FunctionDelegate(NotifyFunction function): + _function(function) + { + } + + FunctionDelegate(const FunctionDelegate& delegate): + AbstractDelegate<void>(delegate), + _function(delegate._function) + { + } + + ~FunctionDelegate() + { + } + + FunctionDelegate& operator = (const FunctionDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + } + return *this; + } + + bool notify(const void* sender) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(const_cast<void*>(sender)); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const FunctionDelegate* pOtherDelegate = dynamic_cast<const FunctionDelegate*>(other.unwrap()); + return pOtherDelegate && _function == pOtherDelegate->_function; + } + + AbstractDelegate<void>* clone() const + { + return new FunctionDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionDelegate(); +}; + + +template <bool senderIsConst> +class FunctionDelegate<void, false, senderIsConst>: public AbstractDelegate<void> +{ +public: + typedef void (*NotifyFunction)(); + + FunctionDelegate(NotifyFunction function): + _function(function) + { + } + + FunctionDelegate(const FunctionDelegate& delegate): + AbstractDelegate<void>(delegate), + _function(delegate._function) + { + } + + ~FunctionDelegate() + { + } + + FunctionDelegate& operator = (const FunctionDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + } + return *this; + } + + bool notify(const void* /*sender*/) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const FunctionDelegate* pOtherDelegate = dynamic_cast<const FunctionDelegate*>(other.unwrap()); + return pOtherDelegate && _function == pOtherDelegate->_function; + } + + AbstractDelegate<void>* clone() const + { + return new FunctionDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionDelegate(); +}; + + +} // namespace Poco + + +#endif // Foundation_FunctionDelegate_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/FunctionPriorityDelegate.h b/contrib/libs/poco/Foundation/include/Poco/FunctionPriorityDelegate.h new file mode 100644 index 0000000000..60e6592048 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/FunctionPriorityDelegate.h @@ -0,0 +1,450 @@ +// +// FunctionPriorityDelegate.h +// +// Library: Foundation +// Package: Events +// Module: FunctionPriorityDelegate +// +// Implementation of the FunctionPriorityDelegate template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_FunctionPriorityDelegate_INCLUDED +#define Foundation_FunctionPriorityDelegate_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractPriorityDelegate.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class TArgs, bool useSender = true, bool senderIsConst = true> +class FunctionPriorityDelegate: public AbstractPriorityDelegate<TArgs> + /// Wraps a freestanding function or static member function + /// for use as a PriorityDelegate. +{ +public: + typedef void (*NotifyFunction)(const void*, TArgs&); + + FunctionPriorityDelegate(NotifyFunction function, int prio): + AbstractPriorityDelegate<TArgs>(prio), + _function(function) + { + } + + FunctionPriorityDelegate(const FunctionPriorityDelegate& delegate): + AbstractPriorityDelegate<TArgs>(delegate), + _function(delegate._function) + { + } + + FunctionPriorityDelegate& operator = (const FunctionPriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + this->_priority = delegate._priority; + } + return *this; + } + + ~FunctionPriorityDelegate() + { + } + + bool notify(const void* sender, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(sender, arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const FunctionPriorityDelegate* pOtherDelegate = dynamic_cast<const FunctionPriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _function == pOtherDelegate->_function; + } + + AbstractDelegate<TArgs>* clone() const + { + return new FunctionPriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionPriorityDelegate(); +}; + + +template <class TArgs> +class FunctionPriorityDelegate<TArgs, true, false>: public AbstractPriorityDelegate<TArgs> +{ +public: + typedef void (*NotifyFunction)(void*, TArgs&); + + FunctionPriorityDelegate(NotifyFunction function, int prio): + AbstractPriorityDelegate<TArgs>(prio), + _function(function) + { + } + + FunctionPriorityDelegate(const FunctionPriorityDelegate& delegate): + AbstractPriorityDelegate<TArgs>(delegate), + _function(delegate._function) + { + } + + FunctionPriorityDelegate& operator = (const FunctionPriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + this->_priority = delegate._priority; + } + return *this; + } + + ~FunctionPriorityDelegate() + { + } + + bool notify(const void* sender, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(const_cast<void*>(sender), arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const FunctionPriorityDelegate* pOtherDelegate = dynamic_cast<const FunctionPriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _function == pOtherDelegate->_function; + } + + AbstractDelegate<TArgs>* clone() const + { + return new FunctionPriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionPriorityDelegate(); +}; + + +template <class TArgs> +class FunctionPriorityDelegate<TArgs, false>: public AbstractPriorityDelegate<TArgs> +{ +public: + typedef void (*NotifyFunction)(TArgs&); + + FunctionPriorityDelegate(NotifyFunction function, int prio): + AbstractPriorityDelegate<TArgs>(prio), + _function(function) + { + } + + FunctionPriorityDelegate(const FunctionPriorityDelegate& delegate): + AbstractPriorityDelegate<TArgs>(delegate), + _function(delegate._function) + { + } + + FunctionPriorityDelegate& operator = (const FunctionPriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + this->_priority = delegate._priority; + } + return *this; + } + + ~FunctionPriorityDelegate() + { + } + + bool notify(const void* sender, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const FunctionPriorityDelegate* pOtherDelegate = dynamic_cast<const FunctionPriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _function == pOtherDelegate->_function; + } + + AbstractDelegate<TArgs>* clone() const + { + return new FunctionPriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionPriorityDelegate(); +}; + + +template <> +class FunctionPriorityDelegate<void, true, true>: public AbstractPriorityDelegate<void> + /// Wraps a freestanding function or static member function + /// for use as a PriorityDelegate. +{ +public: + typedef void (*NotifyFunction)(const void*); + + FunctionPriorityDelegate(NotifyFunction function, int prio): + AbstractPriorityDelegate<void>(prio), + _function(function) + { + } + + FunctionPriorityDelegate(const FunctionPriorityDelegate& delegate): + AbstractPriorityDelegate<void>(delegate), + _function(delegate._function) + { + } + + FunctionPriorityDelegate& operator = (const FunctionPriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + this->_priority = delegate._priority; + } + return *this; + } + + ~FunctionPriorityDelegate() + { + } + + bool notify(const void* sender) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(sender); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const FunctionPriorityDelegate* pOtherDelegate = dynamic_cast<const FunctionPriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _function == pOtherDelegate->_function; + } + + AbstractDelegate<void>* clone() const + { + return new FunctionPriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionPriorityDelegate(); +}; + + +template <> +class FunctionPriorityDelegate<void, true, false>: public AbstractPriorityDelegate<void> +{ +public: + typedef void (*NotifyFunction)(void*); + + FunctionPriorityDelegate(NotifyFunction function, int prio): + AbstractPriorityDelegate<void>(prio), + _function(function) + { + } + + FunctionPriorityDelegate(const FunctionPriorityDelegate& delegate): + AbstractPriorityDelegate<void>(delegate), + _function(delegate._function) + { + } + + FunctionPriorityDelegate& operator = (const FunctionPriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + this->_priority = delegate._priority; + } + return *this; + } + + ~FunctionPriorityDelegate() + { + } + + bool notify(const void* sender) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(const_cast<void*>(sender)); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const FunctionPriorityDelegate* pOtherDelegate = dynamic_cast<const FunctionPriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _function == pOtherDelegate->_function; + } + + AbstractDelegate<void>* clone() const + { + return new FunctionPriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionPriorityDelegate(); +}; + + +template <> +class FunctionPriorityDelegate<void, false>: public AbstractPriorityDelegate<void> +{ +public: + typedef void (*NotifyFunction)(); + + FunctionPriorityDelegate(NotifyFunction function, int prio): + AbstractPriorityDelegate<void>(prio), + _function(function) + { + } + + FunctionPriorityDelegate(const FunctionPriorityDelegate& delegate): + AbstractPriorityDelegate<void>(delegate), + _function(delegate._function) + { + } + + FunctionPriorityDelegate& operator = (const FunctionPriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_function = delegate._function; + this->_priority = delegate._priority; + } + return *this; + } + + ~FunctionPriorityDelegate() + { + } + + bool notify(const void* sender) + { + Mutex::ScopedLock lock(_mutex); + if (_function) + { + (*_function)(); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const FunctionPriorityDelegate* pOtherDelegate = dynamic_cast<const FunctionPriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _function == pOtherDelegate->_function; + } + + AbstractDelegate<void>* clone() const + { + return new FunctionPriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _function = 0; + } + +protected: + NotifyFunction _function; + Mutex _mutex; + +private: + FunctionPriorityDelegate(); +}; + + +} // namespace Poco + + +#endif // Foundation_FunctionPriorityDelegate_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Glob.h b/contrib/libs/poco/Foundation/include/Poco/Glob.h new file mode 100644 index 0000000000..bdaccc6059 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Glob.h @@ -0,0 +1,152 @@ +// +// Glob.h +// +// Library: Foundation +// Package: Filesystem +// Module: Glob +// +// Definition of the Glob class. +// +// Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Glob_INCLUDED +#define Foundation_Glob_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextIterator.h" +#include <set> + + +namespace Poco { + + +class Path; + + +class Foundation_API Glob + /// This class implements glob-style pattern matching + /// as known from Unix shells. + /// + /// In the pattern string, '*' matches any sequence of characters, + /// '?' matches any single character, [SET] matches any single character + /// in the specified set, [!SET] matches any character not in the + /// specified set. + /// + /// A set is composed of characters or ranges; a range looks like + /// character hyphen character (as in 0-9 or A-Z). + /// [0-9a-zA-Z_] is the set of characters allowed in C identifiers. + /// Any other character in the pattern must be matched exactly. + /// + /// To suppress the special syntactic significance of any of '[]*?!-\', + /// and match the character exactly, precede it with a backslash. + /// + /// All strings are assumed to be UTF-8 encoded. +{ +public: + enum Options + /// Flags that modify the matching behavior. + { + GLOB_DEFAULT = 0x00, /// default behavior + GLOB_DOT_SPECIAL = 0x01, /// '*' and '?' do not match '.' at beginning of subject + GLOB_FOLLOW_SYMLINKS = 0x02, /// follow symbolic links + GLOB_CASELESS = 0x04, /// ignore case when comparing characters + GLOB_DIRS_ONLY = 0x80 /// only glob for directories (for internal use only) + }; + + Glob(const std::string& pattern, int options = 0); + /// Creates the Glob, using the given pattern. The pattern + /// must not be an empty string. + /// + /// If the GLOB_DOT_SPECIAL option is specified, '*' and '?' do + /// not match '.' at the beginning of a matched subject. This is useful for + /// making dot-files invisible in good old Unix-style. + + ~Glob(); + /// Destroys the Glob. + + bool match(const std::string& subject); + /// Matches the given subject against the glob pattern. + /// Returns true if the subject matches the pattern, false + /// otherwise. + + static void glob(const std::string& pathPattern, std::set<std::string>& files, int options = 0); + /// Creates a set of files that match the given pathPattern. + /// + /// The path may be give in either Unix, Windows or VMS syntax and + /// is automatically expanded by calling Path::expand(). + /// + /// The pattern may contain wildcard expressions even in intermediate + /// directory names (e.g. /usr/include/*/*.h). + /// + /// Note that, for obvious reasons, escaping characters in a pattern + /// with a backslash does not work in Windows-style paths. + /// + /// Directories that for whatever reason cannot be traversed are + /// ignored. + + static void glob(const char* pathPattern, std::set<std::string>& files, int options = 0); + /// Creates a set of files that match the given pathPattern. + /// + /// The path may be give in either Unix, Windows or VMS syntax and + /// is automatically expanded by calling Path::expand(). + /// + /// The pattern may contain wildcard expressions even in intermediate + /// directory names (e.g. /usr/include/*/*.h). + /// + /// Note that, for obvious reasons, escaping characters in a pattern + /// with a backslash does not work in Windows-style paths. + /// + /// Directories that for whatever reason cannot be traversed are + /// ignored. + + static void glob(const Path& pathPattern, std::set<std::string>& files, int options = 0); + /// Creates a set of files that match the given pathPattern. + /// + /// The pattern may contain wildcard expressions even in intermediate + /// directory names (e.g. /usr/include/*/*.h). + /// + /// Note that, for obvious reasons, escaping characters in a pattern + /// with a backslash does not work in Windows-style paths. + /// + /// Directories that for whatever reason cannot be traversed are + /// ignored. + + static void glob(const Path& pathPattern, const Path& basePath, std::set<std::string>& files, int options = 0); + /// Creates a set of files that match the given pathPattern, starting from basePath. + /// + /// The pattern may contain wildcard expressions even in intermediate + /// directory names (e.g. /usr/include/*/*.h). + /// + /// Note that, for obvious reasons, escaping characters in a pattern + /// with a backslash does not work in Windows-style paths. + /// + /// Directories that for whatever reason cannot be traversed are + /// ignored. + +protected: + bool match(TextIterator& itp, const TextIterator& endp, TextIterator& its, const TextIterator& ends); + bool matchAfterAsterisk(TextIterator itp, const TextIterator& endp, TextIterator its, const TextIterator& ends); + bool matchSet(TextIterator& itp, const TextIterator& endp, int c); + static void collect(const Path& pathPattern, const Path& base, const Path& current, const std::string& pattern, std::set<std::string>& files, int options); + static bool isDirectory(const Path& path, bool followSymlink); + +private: + std::string _pattern; + int _options; + + Glob(); + Glob(const Glob&); + Glob& operator = (const Glob&); +}; + + +} // namespace Poco + + +#endif // Foundation_Glob_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/HMACEngine.h b/contrib/libs/poco/Foundation/include/Poco/HMACEngine.h new file mode 100644 index 0000000000..0593e7d2c1 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/HMACEngine.h @@ -0,0 +1,146 @@ +// +// HMACEngine.h +// +// Library: Foundation +// Package: Crypt +// Module: HMACEngine +// +// Definition of the HMACEngine class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_HMACEngine_INCLUDED +#define Foundation_HMACEngine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" +#include <cstring> + + +namespace Poco { + + +template <class Engine> +class HMACEngine: public DigestEngine + /// This class implementes the HMAC message + /// authentication code algorithm, as specified + /// in RFC 2104. The underlying DigestEngine + /// (MD5Engine, SHA1Engine, etc.) must be given as + /// template argument. + /// Since the HMACEngine is a DigestEngine, it can + /// be used with the DigestStream class to create + /// a HMAC for a stream. +{ +public: + enum + { + BLOCK_SIZE = Engine::BLOCK_SIZE, + DIGEST_SIZE = Engine::DIGEST_SIZE + }; + + HMACEngine(const std::string& passphrase) + { + init(passphrase.data(), passphrase.length()); + } + + HMACEngine(const char* passphrase, std::size_t length) + { + poco_check_ptr (passphrase); + + init(passphrase, length); + } + + ~HMACEngine() + { + std::memset(_ipad, 0, BLOCK_SIZE); + std::memset(_opad, 0, BLOCK_SIZE); + delete [] _ipad; + delete [] _opad; + } + + std::size_t digestLength() const + { + return DIGEST_SIZE; + } + + void reset() + { + _engine.reset(); + _engine.update(_ipad, BLOCK_SIZE); + } + + const DigestEngine::Digest& digest() + { + const DigestEngine::Digest& d = _engine.digest(); + char db[DIGEST_SIZE]; + char* pdb = db; + for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end(); ++it) + *pdb++ = *it; + _engine.reset(); + _engine.update(_opad, BLOCK_SIZE); + _engine.update(db, DIGEST_SIZE); + const DigestEngine::Digest& result = _engine.digest(); + reset(); + return result; + } + +protected: + void init(const char* passphrase, std::size_t length) + { + _ipad = new char[BLOCK_SIZE]; + _opad = new char[BLOCK_SIZE]; + std::memset(_ipad, 0, BLOCK_SIZE); + std::memset(_opad, 0, BLOCK_SIZE); + if (length > BLOCK_SIZE) + { + _engine.reset(); + _engine.update(passphrase, length); + const DigestEngine::Digest& d = _engine.digest(); + char* ipad = _ipad; + char* opad = _opad; + int n = BLOCK_SIZE; + for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end() && n-- > 0; ++it) + { + *ipad++ = *it; + *opad++ = *it; + } + } + else + { + std::memcpy(_ipad, passphrase, length); + std::memcpy(_opad, passphrase, length); + } + for (int i = 0; i < BLOCK_SIZE; ++i) + { + _ipad[i] ^= 0x36; + _opad[i] ^= 0x5c; + } + reset(); + } + + void updateImpl(const void* data, std::size_t length) + { + _engine.update(data, length); + } + +private: + HMACEngine(); + HMACEngine(const HMACEngine&); + HMACEngine& operator = (const HMACEngine&); + + Engine _engine; + char* _ipad; + char* _opad; +}; + + +} // namespace Poco + + +#endif // Foundation_HMACEngine_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Hash.h b/contrib/libs/poco/Foundation/include/Poco/Hash.h new file mode 100644 index 0000000000..7aafb66a69 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Hash.h @@ -0,0 +1,105 @@ +// +// Hash.h +// +// Library: Foundation +// Package: Hashing +// Module: Hash +// +// Definition of the Hash class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Hash_INCLUDED +#define Foundation_Hash_INCLUDED + + +#include "Poco/Foundation.h" +#include <cstddef> + + +namespace Poco { + + +std::size_t Foundation_API hash(Int8 n); +std::size_t Foundation_API hash(UInt8 n); +std::size_t Foundation_API hash(Int16 n); +std::size_t Foundation_API hash(UInt16 n); +std::size_t Foundation_API hash(Int32 n); +std::size_t Foundation_API hash(UInt32 n); +std::size_t Foundation_API hash(Int64 n); +std::size_t Foundation_API hash(UInt64 n); +std::size_t Foundation_API hash(const std::string& str); + + +template <class T> +struct Hash + /// A generic hash function. +{ + std::size_t operator () (T value) const + /// Returns the hash for the given value. + { + return Poco::hash(value); + } +}; + + +// +// inlines +// +inline std::size_t hash(Int8 n) +{ + return static_cast<std::size_t>(n)*2654435761U; +} + + +inline std::size_t hash(UInt8 n) +{ + return static_cast<std::size_t>(n)*2654435761U; +} + + +inline std::size_t hash(Int16 n) +{ + return static_cast<std::size_t>(n)*2654435761U; +} + + +inline std::size_t hash(UInt16 n) +{ + return static_cast<std::size_t>(n)*2654435761U; +} + + +inline std::size_t hash(Int32 n) +{ + return static_cast<std::size_t>(n)*2654435761U; +} + + +inline std::size_t hash(UInt32 n) +{ + return static_cast<std::size_t>(n)*2654435761U; +} + + +inline std::size_t hash(Int64 n) +{ + return static_cast<std::size_t>(n)*2654435761U; +} + + +inline std::size_t hash(UInt64 n) +{ + return static_cast<std::size_t>(n)*2654435761U; +} + + +} // namespace Poco + + +#endif // Foundation_Hash_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/HashFunction.h b/contrib/libs/poco/Foundation/include/Poco/HashFunction.h new file mode 100644 index 0000000000..c451d0699d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/HashFunction.h @@ -0,0 +1,57 @@ +// +// HashFunction.h +// +// Library: Foundation +// Package: Hashing +// Module: HashFunction +// +// Definition of the HashFunction class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_HashFunction_INCLUDED +#define Foundation_HashFunction_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Hash.h" + + +namespace Poco { + + +//@ deprecated +template <class T> +struct HashFunction + /// A generic hash function. +{ + UInt32 operator () (T key, UInt32 maxValue) const + /// Returns the hash value for the given key. + { + return static_cast<UInt32>(Poco::hash(key)) % maxValue; + } +}; + + +//@ deprecated +template <> +struct HashFunction<std::string> + /// A generic hash function. +{ + UInt32 operator () (const std::string& key, UInt32 maxValue) const + /// Returns the hash value for the given key. + { + return static_cast<UInt32>(Poco::hash(key)) % maxValue; + } +}; + + +} // namespace Poco + + +#endif // Foundation_HashFunctions_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/HashMap.h b/contrib/libs/poco/Foundation/include/Poco/HashMap.h new file mode 100644 index 0000000000..5153f2b164 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/HashMap.h @@ -0,0 +1,228 @@ +// +// HashMap.h +// +// Library: Foundation +// Package: Hashing +// Module: HashMap +// +// Definition of the HashMap class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_HashMap_INCLUDED +#define Foundation_HashMap_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/LinearHashTable.h" +#include "Poco/Exception.h" +#include <utility> + + +namespace Poco { + + +template <class Key, class Value> +struct HashMapEntry + /// This class template is used internally by HashMap. +{ + Key first; + Value second; + + HashMapEntry(): + first(), + second() + { + } + + HashMapEntry(const Key& key): + first(key), + second() + { + } + + HashMapEntry(const Key& key, const Value& value): + first(key), + second(value) + { + } + + bool operator == (const HashMapEntry& entry) const + { + return first == entry.first; + } + + bool operator != (const HashMapEntry& entry) const + { + return first != entry.first; + } +}; + + +template <class HME, class KeyHashFunc> +struct HashMapEntryHash + /// This class template is used internally by HashMap. +{ + std::size_t operator () (const HME& entry) const + { + return _func(entry.first); + } + +private: + KeyHashFunc _func; +}; + + +template <class Key, class Mapped, class HashFunc = Hash<Key> > +class HashMap + /// This class implements a map using a LinearHashTable. + /// + /// A HashMap can be used just like a std::map. +{ +public: + typedef Key KeyType; + typedef Mapped MappedType; + typedef Mapped& Reference; + typedef const Mapped& ConstReference; + typedef Mapped* Pointer; + typedef const Mapped* ConstPointer; + + typedef HashMapEntry<Key, Mapped> ValueType; + typedef std::pair<KeyType, MappedType> PairType; + + typedef HashMapEntryHash<ValueType, HashFunc> HashType; + typedef LinearHashTable<ValueType, HashType> HashTable; + + typedef typename HashTable::Iterator Iterator; + typedef typename HashTable::ConstIterator ConstIterator; + + HashMap() + /// Creates an empty HashMap. + { + } + + HashMap(std::size_t initialReserve): + _table(initialReserve) + /// Creates the HashMap with room for initialReserve entries. + { + } + + HashMap& operator = (const HashMap& map) + /// Assigns another HashMap. + { + HashMap tmp(map); + swap(tmp); + return *this; + } + + void swap(HashMap& map) + /// Swaps the HashMap with another one. + { + _table.swap(map._table); + } + + ConstIterator begin() const + { + return _table.begin(); + } + + ConstIterator end() const + { + return _table.end(); + } + + Iterator begin() + { + return _table.begin(); + } + + Iterator end() + { + return _table.end(); + } + + ConstIterator find(const KeyType& key) const + { + ValueType value(key); + return _table.find(value); + } + + Iterator find(const KeyType& key) + { + ValueType value(key); + return _table.find(value); + } + + std::size_t count(const KeyType& key) const + { + ValueType value(key); + return _table.find(value) != _table.end() ? 1 : 0; + } + + std::pair<Iterator, bool> insert(const PairType& pair) + { + ValueType value(pair.first, pair.second); + return _table.insert(value); + } + + std::pair<Iterator, bool> insert(const ValueType& value) + { + return _table.insert(value); + } + + void erase(Iterator it) + { + _table.erase(it); + } + + void erase(const KeyType& key) + { + Iterator it = find(key); + _table.erase(it); + } + + void clear() + { + _table.clear(); + } + + std::size_t size() const + { + return _table.size(); + } + + bool empty() const + { + return _table.empty(); + } + + ConstReference operator [] (const KeyType& key) const + { + ConstIterator it = _table.find(key); + if (it != _table.end()) + return it->second; + else + throw NotFoundException(); + } + + Reference operator [] (const KeyType& key) + { + ValueType value(key); + std::pair<Iterator, bool> res = _table.insert(value); + return res.first->second; + } + +private: + HashTable _table; +}; + + +} // namespace Poco + + +#endif // Foundation_HashMap_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/HashSet.h b/contrib/libs/poco/Foundation/include/Poco/HashSet.h new file mode 100644 index 0000000000..e24560c001 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/HashSet.h @@ -0,0 +1,177 @@ +// +// HashSet.h +// +// Library: Foundation +// Package: Hashing +// Module: HashSet +// +// Definition of the HashSet class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_HashSet_INCLUDED +#define Foundation_HashSet_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/LinearHashTable.h" + + +namespace Poco { + + +template <class Value, class HashFunc = Hash<Value> > +class HashSet + /// This class implements a set using a LinearHashTable. + /// + /// A HashSet can be used just like a std::set. +{ +public: + typedef Value ValueType; + typedef Value& Reference; + typedef const Value& ConstReference; + typedef Value* Pointer; + typedef const Value* ConstPointer; + typedef HashFunc Hash; + + typedef LinearHashTable<ValueType, Hash> HashTable; + + typedef typename HashTable::Iterator Iterator; + typedef typename HashTable::ConstIterator ConstIterator; + + HashSet() + /// Creates an empty HashSet. + { + } + + HashSet(std::size_t initialReserve): + _table(initialReserve) + /// Creates the HashSet, using the given initialReserve. + { + } + + HashSet(const HashSet& set): + _table(set._table) + /// Creates the HashSet by copying another one. + { + } + + ~HashSet() + /// Destroys the HashSet. + { + } + + HashSet& operator = (const HashSet& table) + /// Assigns another HashSet. + { + HashSet tmp(table); + swap(tmp); + return *this; + } + + void swap(HashSet& set) + /// Swaps the HashSet with another one. + { + _table.swap(set._table); + } + + ConstIterator begin() const + /// Returns an iterator pointing to the first entry, if one exists. + { + return _table.begin(); + } + + ConstIterator end() const + /// Returns an iterator pointing to the end of the table. + { + return _table.end(); + } + + Iterator begin() + /// Returns an iterator pointing to the first entry, if one exists. + { + return _table.begin(); + } + + Iterator end() + /// Returns an iterator pointing to the end of the table. + { + return _table.end(); + } + + ConstIterator find(const ValueType& value) const + /// Finds an entry in the table. + { + return _table.find(value); + } + + Iterator find(const ValueType& value) + /// Finds an entry in the table. + { + return _table.find(value); + } + + std::size_t count(const ValueType& value) const + /// Returns the number of elements with the given + /// value, with is either 1 or 0. + { + return _table.count(value); + } + + std::pair<Iterator, bool> insert(const ValueType& value) + /// Inserts an element into the set. + /// + /// If the element already exists in the set, + /// a pair(iterator, false) with iterator pointing to the + /// existing element is returned. + /// Otherwise, the element is inserted an a + /// pair(iterator, true) with iterator + /// pointing to the new element is returned. + { + return _table.insert(value); + } + + void erase(Iterator it) + /// Erases the element pointed to by it. + { + _table.erase(it); + } + + void erase(const ValueType& value) + /// Erases the element with the given value, if it exists. + { + _table.erase(value); + } + + void clear() + /// Erases all elements. + { + _table.clear(); + } + + std::size_t size() const + /// Returns the number of elements in the table. + { + return _table.size(); + } + + bool empty() const + /// Returns true iff the table is empty. + { + return _table.empty(); + } + +private: + HashTable _table; +}; + + +} // namespace Poco + + +#endif // Foundation_HashSet_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/HashStatistic.h b/contrib/libs/poco/Foundation/include/Poco/HashStatistic.h new file mode 100644 index 0000000000..ac413fb09a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/HashStatistic.h @@ -0,0 +1,126 @@ +// +// HashStatistic.h +// +// Library: Foundation +// Package: Hashing +// Module: HashStatistic +// +// Definition of the HashStatistic class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_HashStatistic_INCLUDED +#define Foundation_HashStatistic_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> + + +namespace Poco { + + +//@ deprecated +class Foundation_API HashStatistic + /// HashStatistic class bundles statistical information on the current state of a HashTable +{ +public: + HashStatistic( + UInt32 tableSize, + UInt32 numEntries, + UInt32 numZeroEntries, + UInt32 maxEntry, + std::vector<UInt32> details = std::vector<UInt32>()); + /// Creates the HashStatistic. + + virtual ~HashStatistic(); + /// Destroys the HashStatistic. + + UInt32 maxPositionsOfTable() const; + /// Returns the maximum number of different hash values possible for the table + + UInt32 numberOfEntries() const; + /// Returns the total number of entries currently stored in the HashTable + + UInt32 numberOfZeroPositions() const; + /// Returns the number of hash positions that contain no entry. + + double avgEntriesPerHash() const; + /// Returns the average number of entries per position in the Hashtable, the higher this value the less efficient + /// performs hashing. If a large value is returned and getNumberOfZeroPositions also returns a large value, this + /// indicates an inefficient hashing function. If the number of zero entries is low, resizing the HashTable, should + /// be enough to improve performance + + double avgEntriesPerHashExclZeroEntries() const; + /// Same as getAvgEntriesPerHash but hash values that contain no entry are ignored, + /// getAvgEntriesPerHashExclZeroEntries >= getAvgEntriesPerHash will always be true. + + UInt32 maxEntriesPerHash() const; + /// Returns the maximum number of entries per hash value found in the current table. + + const std::vector<UInt32> detailedEntriesPerHash() const; + /// Will either be an empty vector or will contain for each possible hash value, the number of entries currently stored + + std::string toString() const; + /// Converts the whole data structure into a string. + +private: + UInt32 _sizeOfTable; + UInt32 _numberOfEntries; + UInt32 _numZeroEntries; + UInt32 _maxEntriesPerHash; + std::vector<UInt32> _detailedEntriesPerHash; +}; + + +inline UInt32 HashStatistic::maxPositionsOfTable() const +{ + return _sizeOfTable; +} + + +inline UInt32 HashStatistic::numberOfEntries() const +{ + return _numberOfEntries; +} + + +inline UInt32 HashStatistic::numberOfZeroPositions() const +{ + return _numZeroEntries; +} + + +inline double HashStatistic::avgEntriesPerHash() const +{ + return ((double) numberOfEntries()) / maxPositionsOfTable(); +} + + +inline double HashStatistic::avgEntriesPerHashExclZeroEntries() const +{ + return ((double) numberOfEntries()) / (maxPositionsOfTable() - numberOfZeroPositions()); +} + + +inline UInt32 HashStatistic::maxEntriesPerHash() const +{ + return _maxEntriesPerHash; +} + + +inline const std::vector<UInt32> HashStatistic::detailedEntriesPerHash() const +{ + return _detailedEntriesPerHash; +} + + +} // namespace Poco + + +#endif // Foundation_HashStatistic_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/HashTable.h b/contrib/libs/poco/Foundation/include/Poco/HashTable.h new file mode 100644 index 0000000000..e71af1e12c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/HashTable.h @@ -0,0 +1,369 @@ +// +// HashTable.h +// +// Library: Foundation +// Package: Hashing +// Module: HashTable +// +// Definition of the HashTable class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_HashTable_INCLUDED +#define Foundation_HashTable_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/HashFunction.h" +#include "Poco/HashStatistic.h" +#include <vector> +#include <map> +#include <cstddef> +#include <cstring> + + +namespace Poco { + + +//@ deprecated +template <class Key, class Value, class KeyHashFunction = HashFunction<Key> > +class HashTable + /// A HashTable stores a key value pair that can be looked up via a hashed key. + /// + /// Collision handling is done via overflow maps(!). With small hash tables performance of this + /// data struct will be closer to that a map than a hash table, i.e. slower. On the plus side, + /// this class offers remove operations. Also HashTable full errors are not possible. If a fast + /// HashTable implementation is needed and the remove operation is not required, use SimpleHashTable + /// instead. + /// + /// This class is NOT thread safe. +{ +public: + typedef std::map<Key, Value> HashEntryMap; + typedef HashEntryMap** HashTableVector; + + typedef typename HashEntryMap::const_iterator ConstIterator; + typedef typename HashEntryMap::iterator Iterator; + + HashTable(UInt32 initialSize = 251): + _entries(0), + _size(0), + _maxCapacity(initialSize) + /// Creates the HashTable. + { + _entries = new HashEntryMap*[initialSize]; + memset(_entries, '\0', sizeof(HashEntryMap*)*initialSize); + } + + HashTable(const HashTable& ht): + _entries(new HashEntryMap*[ht._maxCapacity]), + _size(ht._size), + _maxCapacity(ht._maxCapacity) + { + for (UInt32 i = 0; i < _maxCapacity; ++i) + { + if (ht._entries[i]) + _entries[i] = new HashEntryMap(ht._entries[i]->begin(), ht._entries[i]->end()); + else + _entries[i] = 0; + } + } + + ~HashTable() + /// Destroys the HashTable. + { + clear(); + } + + HashTable& operator = (const HashTable& ht) + { + if (this != &ht) + { + clear(); + _maxCapacity = ht._maxCapacity; + poco_assert_dbg (_entries == 0); + _entries = new HashEntryMap*[_maxCapacity]; + _size = ht._size; + + for (UInt32 i = 0; i < _maxCapacity; ++i) + { + if (ht._entries[i]) + _entries[i] = new HashEntryMap(ht._entries[i]->begin(), ht._entries[i]->end()); + else + _entries[i] = 0; + } + } + return *this; + } + + void clear() + { + if (!_entries) + return; + for (UInt32 i = 0; i < _maxCapacity; ++i) + { + delete _entries[i]; + } + delete[] _entries; + _entries = 0; + _size = 0; + _maxCapacity = 0; + } + + UInt32 insert(const Key& key, const Value& value) + /// Returns the hash value of the inserted item. + /// Throws an exception if the entry was already inserted + { + UInt32 hsh = hash(key); + insertRaw(key, hsh, value); + return hsh; + } + + Value& insertRaw(const Key& key, UInt32 hsh, const Value& value) + /// Returns the hash value of the inserted item. + /// Throws an exception if the entry was already inserted + { + if (!_entries[hsh]) + _entries[hsh] = new HashEntryMap(); + std::pair<typename HashEntryMap::iterator, bool> res(_entries[hsh]->insert(std::make_pair(key, value))); + if (!res.second) + throw InvalidArgumentException("HashTable::insert, key already exists."); + _size++; + return res.first->second; + } + + UInt32 update(const Key& key, const Value& value) + /// Returns the hash value of the inserted item. + /// Replaces an existing entry if it finds one + { + UInt32 hsh = hash(key); + updateRaw(key, hsh, value); + return hsh; + } + + void updateRaw(const Key& key, UInt32 hsh, const Value& value) + /// Returns the hash value of the inserted item. + /// Replaces an existing entry if it finds one + { + if (!_entries[hsh]) + _entries[hsh] = new HashEntryMap(); + std::pair<Iterator, bool> res = _entries[hsh]->insert(std::make_pair(key, value)); + if (res.second == false) + res.first->second = value; + else + _size++; + } + + void remove(const Key& key) + { + UInt32 hsh = hash(key); + removeRaw(key, hsh); + } + + void removeRaw(const Key& key, UInt32 hsh) + /// Performance version, allows to specify the hash value + { + if (_entries[hsh]) + { + _size -= _entries[hsh]->erase(key); + } + } + + UInt32 hash(const Key& key) const + { + return _hash(key, _maxCapacity); + } + + const Value& get(const Key& key) const + /// Throws an exception if the value does not exist + { + UInt32 hsh = hash(key); + return getRaw(key, hsh); + } + + const Value& getRaw(const Key& key, UInt32 hsh) const + /// Throws an exception if the value does not exist + { + if (!_entries[hsh]) + throw InvalidArgumentException("key not found"); + + ConstIterator it = _entries[hsh]->find(key); + if (it == _entries[hsh]->end()) + throw InvalidArgumentException("key not found"); + + return it->second; + } + + Value& get(const Key& key) + /// Throws an exception if the value does not exist + { + UInt32 hsh = hash(key); + return const_cast<Value&>(getRaw(key, hsh)); + } + + const Value& operator [] (const Key& key) const + { + return get(key); + } + + Value& operator [] (const Key& key) + { + UInt32 hsh = hash(key); + + if (!_entries[hsh]) + return insertRaw(key, hsh, Value()); + + ConstIterator it = _entries[hsh]->find(key); + if (it == _entries[hsh]->end()) + return insertRaw(key, hsh, Value()); + + return it->second; + } + + const Key& getKeyRaw(const Key& key, UInt32 hsh) + /// Throws an exception if the key does not exist. returns a reference to the internally + /// stored key. Useful when someone does an insert and wants for performance reason only to store + /// a pointer to the key in another collection + { + if (!_entries[hsh]) + throw InvalidArgumentException("key not found"); + ConstIterator it = _entries[hsh]->find(key); + if (it == _entries[hsh]->end()) + throw InvalidArgumentException("key not found"); + return it->first; + } + + bool get(const Key& key, Value& v) const + /// Sets v to the found value, returns false if no value was found + { + UInt32 hsh = hash(key); + return getRaw(key, hsh, v); + } + + bool getRaw(const Key& key, UInt32 hsh, Value& v) const + /// Sets v to the found value, returns false if no value was found + { + if (!_entries[hsh]) + return false; + + ConstIterator it = _entries[hsh]->find(key); + if (it == _entries[hsh]->end()) + return false; + + v = it->second; + return true; + } + + bool exists(const Key& key) + { + UInt32 hsh = hash(key); + return existsRaw(key, hsh); + } + + bool existsRaw(const Key& key, UInt32 hsh) + { + return _entries[hsh] && (_entries[hsh]->end() != _entries[hsh]->find(key)); + } + + std::size_t size() const + /// Returns the number of elements already inserted into the HashTable + { + return _size; + } + + UInt32 maxCapacity() const + { + return _maxCapacity; + } + + void resize(UInt32 newSize) + /// Resizes the hashtable, rehashes all existing entries. Expensive! + { + if (_maxCapacity != newSize) + { + HashTableVector cpy = _entries; + _entries = 0; + UInt32 oldSize = _maxCapacity; + _maxCapacity = newSize; + _entries = new HashEntryMap*[_maxCapacity]; + memset(_entries, '\0', sizeof(HashEntryMap*)*_maxCapacity); + + if (_size == 0) + { + // no data was yet inserted + delete[] cpy; + return; + } + _size = 0; + for (UInt32 i = 0; i < oldSize; ++i) + { + if (cpy[i]) + { + ConstIterator it = cpy[i]->begin(); + ConstIterator itEnd = cpy[i]->end(); + for (; it != itEnd; ++it) + { + insert(it->first, it->second); + } + delete cpy[i]; + } + } + delete[] cpy; + } + } + + HashStatistic currentState(bool details = false) const + /// Returns the current internal state + { + UInt32 numberOfEntries = (UInt32)_size; + UInt32 numZeroEntries = 0; + UInt32 maxEntriesPerHash = 0; + std::vector<UInt32> detailedEntriesPerHash; + #ifdef _DEBUG + UInt32 totalSize = 0; + #endif + for (UInt32 i = 0; i < _maxCapacity; ++i) + { + if (_entries[i]) + { + UInt32 size = (UInt32)_entries[i]->size(); + poco_assert_dbg(size != 0); + if (size > maxEntriesPerHash) + maxEntriesPerHash = size; + if (details) + detailedEntriesPerHash.push_back(size); + #ifdef _DEBUG + totalSize += size; + #endif + } + else + { + numZeroEntries++; + if (details) + detailedEntriesPerHash.push_back(0); + } + } + #ifdef _DEBUG + poco_assert_dbg(totalSize == numberOfEntries); + #endif + return HashStatistic(_maxCapacity, numberOfEntries, numZeroEntries, maxEntriesPerHash, detailedEntriesPerHash); + } + +private: + HashTableVector _entries; + std::size_t _size; + UInt32 _maxCapacity; + KeyHashFunction _hash; +}; + + +} // namespace Poco + + +#endif // Foundation_HashTable_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/HexBinaryDecoder.h b/contrib/libs/poco/Foundation/include/Poco/HexBinaryDecoder.h new file mode 100644 index 0000000000..7aab0f6cd2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/HexBinaryDecoder.h @@ -0,0 +1,94 @@ +// +// HexBinaryDecoder.h +// +// Library: Foundation +// Package: Streams +// Module: HexBinary +// +// Definition of the HexBinaryDecoder class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_HexBinaryDecoder_INCLUDED +#define Foundation_HexBinaryDecoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <istream> + + +namespace Poco { + + +class Foundation_API HexBinaryDecoderBuf: public UnbufferedStreamBuf + /// This streambuf decodes all hexBinary-encoded data read + /// from the istream connected to it. + /// In hexBinary encoding, each binary octet is encoded as a character tuple, + /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. + /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), + /// section 3.2.15. + /// + /// Note: For performance reasons, the characters + /// are read directly from the given istream's + /// underlying streambuf, so the state + /// of the istream will not reflect that of + /// its streambuf. +{ +public: + HexBinaryDecoderBuf(std::istream& istr); + ~HexBinaryDecoderBuf(); + +private: + int readFromDevice(); + int readOne(); + + std::streambuf& _buf; +}; + + +class Foundation_API HexBinaryDecoderIOS: public virtual std::ios + /// The base class for HexBinaryDecoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + HexBinaryDecoderIOS(std::istream& istr); + ~HexBinaryDecoderIOS(); + HexBinaryDecoderBuf* rdbuf(); + +protected: + HexBinaryDecoderBuf _buf; +}; + + +class Foundation_API HexBinaryDecoder: public HexBinaryDecoderIOS, public std::istream + /// This istream decodes all hexBinary-encoded data read + /// from the istream connected to it. + /// In hexBinary encoding, each binary octet is encoded as a character tuple, + /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. + /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), + /// section 3.2.15. + /// + /// Note: For performance reasons, the characters + /// are read directly from the given istream's + /// underlying streambuf, so the state + /// of the istream will not reflect that of + /// its streambuf. +{ +public: + HexBinaryDecoder(std::istream& istr); + ~HexBinaryDecoder(); +}; + + +} // namespace Poco + + +#endif // Foundation_HexBinaryDecoder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/HexBinaryEncoder.h b/contrib/libs/poco/Foundation/include/Poco/HexBinaryEncoder.h new file mode 100644 index 0000000000..453c3cd821 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/HexBinaryEncoder.h @@ -0,0 +1,117 @@ +// +// HexBinaryEncoder.h +// +// Library: Foundation +// Package: Streams +// Module: HexBinary +// +// Definition of the HexBinaryEncoder class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_HexBinaryEncoder_INCLUDED +#define Foundation_HexBinaryEncoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <ostream> + + +namespace Poco { + + +class Foundation_API HexBinaryEncoderBuf: public UnbufferedStreamBuf + /// This streambuf encodes all data written + /// to it in hexBinary encoding and forwards it to a connected + /// ostream. + /// In hexBinary encoding, each binary octet is encoded as a character tuple, + /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. + /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), + /// section 3.2.15. + /// + /// Note: The characters are directly written + /// to the ostream's streambuf, thus bypassing + /// the ostream. The ostream's state is therefore + /// not updated to match the buffer's state. +{ +public: + HexBinaryEncoderBuf(std::ostream& ostr); + ~HexBinaryEncoderBuf(); + + int close(); + /// Closes the stream buffer. + + void setLineLength(int lineLength); + /// Specify the line length. + /// + /// After the given number of characters have been written, + /// a newline character will be written. + /// + /// Specify 0 for an unlimited line length. + + int getLineLength() const; + /// Returns the currently set line length. + + void setUppercase(bool flag = true); + /// Specify whether hex digits a-f are written in upper or lower case. + +private: + int writeToDevice(char c); + + int _pos; + int _lineLength; + int _uppercase; + std::streambuf& _buf; +}; + + +class Foundation_API HexBinaryEncoderIOS: public virtual std::ios + /// The base class for HexBinaryEncoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + HexBinaryEncoderIOS(std::ostream& ostr); + ~HexBinaryEncoderIOS(); + int close(); + HexBinaryEncoderBuf* rdbuf(); + +protected: + HexBinaryEncoderBuf _buf; +}; + + +class Foundation_API HexBinaryEncoder: public HexBinaryEncoderIOS, public std::ostream + /// This ostream encodes all data + /// written to it in BinHex encoding and forwards it to + /// a connected ostream. + /// Always call close() when done + /// writing data, to ensure proper + /// completion of the encoding operation. + /// In hexBinary encoding, each binary octet is encoded as a character tuple, + /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. + /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), + /// section 3.2.15. + /// + /// Note: The characters are directly written + /// to the ostream's streambuf, thus bypassing + /// the ostream. The ostream's state is therefore + /// not updated to match the buffer's state. +{ +public: + HexBinaryEncoder(std::ostream& ostr); + ~HexBinaryEncoder(); +}; + + +} // namespace Poco + + +#endif // Foundation_HexBinaryEncoder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/InflatingStream.h b/contrib/libs/poco/Foundation/include/Poco/InflatingStream.h new file mode 100644 index 0000000000..792677be71 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/InflatingStream.h @@ -0,0 +1,211 @@ +// +// InflatingStream.h +// +// Library: Foundation +// Package: Streams +// Module: ZLibStream +// +// Definition of the InflatingInputStream and InflatingOutputStream classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_InflatingStream_INCLUDED +#define Foundation_InflatingStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedStreamBuf.h" +#include <istream> +#include <ostream> +#if defined(POCO_UNBUNDLED) +#include <zlib.h> +#else +#error #include "Poco/zlib.h" +#endif + + +namespace Poco { + + +class Foundation_API InflatingStreamBuf: public BufferedStreamBuf + /// This is the streambuf class used by InflatingInputStream and InflatingOutputStream. + /// The actual work is delegated to zlib (see http://zlib.net). + /// Both zlib (deflate) streams and gzip streams are supported. + /// Output streams should always call close() to ensure + /// proper completion of decompression. +{ +public: + enum StreamType + { + STREAM_ZLIB, /// Expect a zlib header, use Adler-32 checksum. + STREAM_GZIP, /// Expect a gzip header, use CRC-32 checksum. + STREAM_ZIP /// STREAM_ZIP is handled as STREAM_ZLIB, except that we do not check the ADLER32 value (must be checked by caller) + }; + + InflatingStreamBuf(std::istream& istr, StreamType type); + /// Creates an InflatingStreamBuf for expanding the compressed data read from + /// the give input stream. + + InflatingStreamBuf(std::istream& istr, int windowBits); + /// Creates an InflatingStreamBuf for expanding the compressed data read from + /// the given input stream. + /// + /// Please refer to the zlib documentation of inflateInit2() for a description + /// of the windowBits parameter. + + InflatingStreamBuf(std::ostream& ostr, StreamType type); + /// Creates an InflatingStreamBuf for expanding the compressed data passed through + /// and forwarding it to the given output stream. + + InflatingStreamBuf(std::ostream& ostr, int windowBits); + /// Creates an InflatingStreamBuf for expanding the compressed data passed through + /// and forwarding it to the given output stream. + /// + /// Please refer to the zlib documentation of inflateInit2() for a description + /// of the windowBits parameter. + + ~InflatingStreamBuf(); + /// Destroys the InflatingStreamBuf. + + int close(); + /// Finishes up the stream. + /// + /// Must be called when inflating to an output stream. + + void reset(); + /// Resets the stream buffer. + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + int sync(); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024, + INFLATE_BUFFER_SIZE = 32768 + }; + + std::istream* _pIstr; + std::ostream* _pOstr; + char* _buffer; + z_stream _zstr; + bool _eof; + bool _check; +}; + + +class Foundation_API InflatingIOS: public virtual std::ios + /// The base class for InflatingOutputStream and InflatingInputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + InflatingIOS(std::ostream& ostr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); + /// Creates an InflatingIOS for expanding the compressed data passed through + /// and forwarding it to the given output stream. + + InflatingIOS(std::ostream& ostr, int windowBits); + /// Creates an InflatingIOS for expanding the compressed data passed through + /// and forwarding it to the given output stream. + /// + /// Please refer to the zlib documentation of inflateInit2() for a description + /// of the windowBits parameter. + + InflatingIOS(std::istream& istr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); + /// Creates an InflatingIOS for expanding the compressed data read from + /// the given input stream. + + InflatingIOS(std::istream& istr, int windowBits); + /// Creates an InflatingIOS for expanding the compressed data read from + /// the given input stream. + /// + /// Please refer to the zlib documentation of inflateInit2() for a description + /// of the windowBits parameter. + + ~InflatingIOS(); + /// Destroys the InflatingIOS. + + InflatingStreamBuf* rdbuf(); + /// Returns a pointer to the underlying stream buffer. + +protected: + InflatingStreamBuf _buf; +}; + + +class Foundation_API InflatingOutputStream: public std::ostream, public InflatingIOS + /// This stream decompresses all data passing through it + /// using zlib's inflate algorithm. + /// + /// After all data has been written to the stream, close() + /// must be called to ensure completion of decompression. +{ +public: + InflatingOutputStream(std::ostream& ostr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); + /// Creates an InflatingOutputStream for expanding the compressed data passed through + /// and forwarding it to the given output stream. + + InflatingOutputStream(std::ostream& ostr, int windowBits); + /// Creates an InflatingOutputStream for expanding the compressed data passed through + /// and forwarding it to the given output stream. + /// + /// Please refer to the zlib documentation of inflateInit2() for a description + /// of the windowBits parameter. + + ~InflatingOutputStream(); + /// Destroys the InflatingOutputStream. + + int close(); + /// Finishes up the stream. + /// + /// Must be called to ensure all data is properly written to + /// the target output stream. +}; + + +class Foundation_API InflatingInputStream: public std::istream, public InflatingIOS + /// This stream decompresses all data passing through it + /// using zlib's inflate algorithm. + /// Example: + /// std::ifstream istr("data.gz", std::ios::binary); + /// InflatingInputStream inflater(istr, InflatingStreamBuf::STREAM_GZIP); + /// std::string data; + /// inflater >> data; + /// + /// The underlying input stream can contain more than one gzip/deflate stream. + /// After a gzip/deflate stream has been processed, reset() can be called + /// to inflate the next stream. +{ +public: + InflatingInputStream(std::istream& istr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); + /// Creates an InflatingInputStream for expanding the compressed data read from + /// the given input stream. + + InflatingInputStream(std::istream& istr, int windowBits); + /// Creates an InflatingInputStream for expanding the compressed data read from + /// the given input stream. + /// + /// Please refer to the zlib documentation of inflateInit2() for a description + /// of the windowBits parameter. + + ~InflatingInputStream(); + /// Destroys the InflatingInputStream. + + void reset(); + /// Resets the zlib machinery so that another zlib stream can be read from + /// the same underlying input stream. +}; + + +} // namespace Poco + + +#endif // Foundation_InflatingStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Instantiator.h b/contrib/libs/poco/Foundation/include/Poco/Instantiator.h new file mode 100644 index 0000000000..ce21ebc12e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Instantiator.h @@ -0,0 +1,82 @@ +// +// Instantiator.h +// +// Library: Foundation +// Package: Core +// Module: Instantiator +// +// Definition of the Instantiator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Instantiator_INCLUDED +#define Foundation_Instantiator_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template <class Base> +class AbstractInstantiator + /// The common base class for all Instantiator instantiations. + /// Used by DynamicFactory. +{ +public: + AbstractInstantiator() + /// Creates the AbstractInstantiator. + { + } + + virtual ~AbstractInstantiator() + /// Destroys the AbstractInstantiator. + { + } + + virtual Base* createInstance() const = 0; + /// Creates an instance of a concrete subclass of Base. + +private: + AbstractInstantiator(const AbstractInstantiator&); + AbstractInstantiator& operator = (const AbstractInstantiator&); +}; + + +template <class C, class Base> +class Instantiator: public AbstractInstantiator<Base> + /// A template class for the easy instantiation of + /// instantiators. + /// + /// For the Instantiator to work, the class of which + /// instances are to be instantiated must have a no-argument + /// constructor. +{ +public: + Instantiator() + /// Creates the Instantiator. + { + } + + virtual ~Instantiator() + /// Destroys the Instantiator. + { + } + + Base* createInstance() const + { + return new C; + } +}; + + +} // namespace Poco + + +#endif // Foundation_Instantiator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/JSONString.h b/contrib/libs/poco/Foundation/include/Poco/JSONString.h new file mode 100644 index 0000000000..b4446efce7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/JSONString.h @@ -0,0 +1,93 @@ +// +// JSONString.h +// +// Library: Foundation +// Package: Core +// Module: String +// +// JSONString utility functions. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_JSONString_INCLUDED +#define Foundation_JSONString_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +enum JSONOptions +{ + JSON_PRESERVE_KEY_ORDER = 1, + /// Applies to JSON::Object. If specified, the Object will + /// preserve the items insertion order. Otherwise, items + /// will be sorted by keys. + /// + /// Has no effect on toJSON() function. + + JSON_ESCAPE_UNICODE = 2, + /// If specified, when the object is stringified, all + /// unicode characters will be escaped in the resulting + /// string. + + JSON_WRAP_STRINGS = 4 + /// If specified, the object will preserve the items + /// insertion order. Otherwise, items will be sorted + /// by keys. + }; + + +//@ deprecated +void Foundation_API toJSON(const std::string& value, std::ostream& out, bool wrap = true); + /// Formats string value into the supplied output stream by + /// escaping control and ALL Unicode characters. + /// If wrap is true, the resulting string is enclosed in double quotes. + /// + /// This function is deprecated, please use + /// + /// void Poco::toJSON(const std::string&, std::ostream&, int) + + +//@ deprecated +std::string Foundation_API toJSON(const std::string& value, bool wrap = true); + /// Formats string value by escaping control and ALL Unicode characters. + /// If wrap is true, the resulting string is enclosed in double quotes + /// + /// Returns formatted string. + /// + /// This function is deprecated, please use + /// + /// std::string Poco::toJSON(const std::string&, int) + + +void Foundation_API toJSON(const std::string& value, std::ostream& out, int options); + /// Formats string value into the supplied output stream by + /// escaping control characters. + /// If JSON_WRAP_STRINGS is in options, the resulting strings is enclosed in double quotes + /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise + /// only the compulsory ones. + + +std::string Foundation_API toJSON(const std::string& value, int options); + /// Formats string value by escaping control characters. + /// If JSON_WRAP_STRINGS is in options, the resulting string is enclosed in double quotes + /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise + /// only the compulsory ones. + /// + /// Returns formatted string. + /// If escapeAllUnicode is true, all unicode characters will be escaped, otherwise only the compulsory ones. + + + +} // namespace Poco + + +#endif // Foundation_JSONString_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/KeyValueArgs.h b/contrib/libs/poco/Foundation/include/Poco/KeyValueArgs.h new file mode 100644 index 0000000000..cdcc4e1cec --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/KeyValueArgs.h @@ -0,0 +1,73 @@ +// +// KeyValueArgs.h +// +// Library: Foundation +// Package: Cache +// Module: KeyValueArgs +// +// Definition of the KeyValueArgs class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_KeyValueArgs_INCLUDED +#define Foundation_KeyValueArgs_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template <class TKey, class TValue> +class KeyValueArgs + /// Simply event arguments class to transfer a key and a value via an event call. + /// Note that key and value are *NOT* copied, only references to them are stored. +{ +public: + KeyValueArgs(const TKey& aKey, const TValue& aVal): + _key(aKey), + _value(aVal) + { + } + + KeyValueArgs(const KeyValueArgs& args): + _key(args._key), + _value(args._value) + { + } + + ~KeyValueArgs() + { + } + + const TKey& key() const + /// Returns a reference to the key, + { + return _key; + } + + const TValue& value() const + /// Returns a Reference to the value. + { + return _value; + } + +protected: + const TKey& _key; + const TValue& _value; + +private: + KeyValueArgs& operator = (const KeyValueArgs& args); +}; + + +} // namespace Poco + + +#endif // Foundation_KeyValueArgs_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LRUCache.h b/contrib/libs/poco/Foundation/include/Poco/LRUCache.h new file mode 100644 index 0000000000..7f8f0debd9 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LRUCache.h @@ -0,0 +1,56 @@ +// +// LRUCache.h +// +// Library: Foundation +// Package: Cache +// Module: LRUCache +// +// Definition of the LRUCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LRUCache_INCLUDED +#define Foundation_LRUCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/LRUStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class LRUCache: public AbstractCache<TKey, TValue, LRUStrategy<TKey, TValue>, TMutex, TEventMutex> + /// An LRUCache implements Least Recently Used caching. The default size for a cache is 1024 entries. +{ +public: + LRUCache(long size = 1024): + AbstractCache<TKey, TValue, LRUStrategy<TKey, TValue>, TMutex, TEventMutex>(LRUStrategy<TKey, TValue>(size)) + { + } + + ~LRUCache() + { + } + +private: + LRUCache(const LRUCache& aCache); + LRUCache& operator = (const LRUCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_LRUCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LRUStrategy.h b/contrib/libs/poco/Foundation/include/Poco/LRUStrategy.h new file mode 100644 index 0000000000..795623872e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LRUStrategy.h @@ -0,0 +1,140 @@ +// +// LRUStrategy.h +// +// Library: Foundation +// Package: Cache +// Module: LRUStrategy +// +// Definition of the LRUStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LRUStrategy_INCLUDED +#define Foundation_LRUStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/AbstractStrategy.h" +#include "Poco/EventArgs.h" +#include "Poco/Exception.h" +#include <list> +#include <map> +#include <cstddef> + + +namespace Poco { + + +template <class TKey, class TValue> +class LRUStrategy: public AbstractStrategy<TKey, TValue> + /// An LRUStrategy implements least recently used cache replacement. +{ +public: + typedef std::list<TKey> Keys; + typedef typename Keys::iterator Iterator; + typedef typename Keys::const_iterator ConstIterator; + typedef std::map<TKey, Iterator> KeyIndex; + typedef typename KeyIndex::iterator IndexIterator; + typedef typename KeyIndex::const_iterator ConstIndexIterator; + +public: + LRUStrategy(std::size_t size): + _size(size) + { + if (_size < 1) throw InvalidArgumentException("size must be > 0"); + } + + ~LRUStrategy() + { + } + + void onAdd(const void*, const KeyValueArgs <TKey, TValue>& args) + { + _keys.push_front(args.key()); + std::pair<IndexIterator, bool> stat = _keyIndex.insert(std::make_pair(args.key(), _keys.begin())); + if (!stat.second) + { + stat.first->second = _keys.begin(); + } + } + + void onRemove(const void*, const TKey& key) + { + IndexIterator it = _keyIndex.find(key); + + if (it != _keyIndex.end()) + { + _keys.erase(it->second); + _keyIndex.erase(it); + } + } + + void onGet(const void*, const TKey& key) + { + // LRU: in case of an hit, move to begin + IndexIterator it = _keyIndex.find(key); + + if (it != _keyIndex.end()) + { + _keys.splice(_keys.begin(), _keys, it->second); //_keys.erase(it->second)+_keys.push_front(key); + it->second = _keys.begin(); + } + } + + void onClear(const void*, const EventArgs& /*args*/) + { + _keys.clear(); + _keyIndex.clear(); + } + + void onIsValid(const void*, ValidArgs<TKey>& args) + { + if (_keyIndex.find(args.key()) == _keyIndex.end()) + { + args.invalidate(); + } + } + + void onReplace(const void*, std::set<TKey>& elemsToRemove) + { + // Note: replace only informs the cache which elements + // it would like to remove! + // it does not remove them on its own! + std::size_t curSize = _keyIndex.size(); + + if (curSize < _size) + { + return; + } + + std::size_t diff = curSize - _size; + Iterator it = --_keys.end(); //--keys can never be invoked on an empty list due to the minSize==1 requirement of LRU + std::size_t i = 0; + + while (i++ < diff) + { + elemsToRemove.insert(*it); + if (it != _keys.begin()) + { + --it; + } + } + } + +protected: + std::size_t _size; /// Number of keys the cache can store. + Keys _keys; + KeyIndex _keyIndex; /// For faster access to _keys +}; + + +} // namespace Poco + + +#endif // Foundation_LRUStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Latin1Encoding.h b/contrib/libs/poco/Foundation/include/Poco/Latin1Encoding.h new file mode 100644 index 0000000000..b1b987e0a7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Latin1Encoding.h @@ -0,0 +1,51 @@ +// +// Latin1Encoding.h +// +// Library: Foundation +// Package: Text +// Module: Latin1Encoding +// +// Definition of the Latin1Encoding class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Latin1Encoding_INCLUDED +#define Foundation_Latin1Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Latin1Encoding: public TextEncoding + /// ISO Latin-1 (8859-1) text encoding. +{ +public: + Latin1Encoding(); + ~Latin1Encoding(); + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Latin1Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Latin2Encoding.h b/contrib/libs/poco/Foundation/include/Poco/Latin2Encoding.h new file mode 100644 index 0000000000..ac1cfecde3 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Latin2Encoding.h @@ -0,0 +1,54 @@ +// +// Latin2Encoding.h +// +// Library: Foundation +// Package: Text +// Module: Latin2Encoding +// +// Definition of the Latin2Encoding class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Latin2Encoding_INCLUDED +#define Foundation_Latin2Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Latin2Encoding: public TextEncoding + /// ISO Latin-2 (8859-2) text encoding. + /// + /// Latin-2 is basically Latin-1 with the EURO sign plus + /// some other minor changes. +{ +public: + Latin2Encoding(); + virtual ~Latin2Encoding(); + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Latin2Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Latin9Encoding.h b/contrib/libs/poco/Foundation/include/Poco/Latin9Encoding.h new file mode 100644 index 0000000000..d2b7a1ca79 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Latin9Encoding.h @@ -0,0 +1,54 @@ +// +// Latin9Encoding.h +// +// Library: Foundation +// Package: Text +// Module: Latin9Encoding +// +// Definition of the Latin9Encoding class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Latin9Encoding_INCLUDED +#define Foundation_Latin9Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Latin9Encoding: public TextEncoding + /// ISO Latin-9 (8859-15) text encoding. + /// + /// Latin-9 is basically Latin-1 with the EURO sign plus + /// some other minor changes. +{ +public: + Latin9Encoding(); + ~Latin9Encoding(); + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Latin9Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LineEndingConverter.h b/contrib/libs/poco/Foundation/include/Poco/LineEndingConverter.h new file mode 100644 index 0000000000..d23414c357 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LineEndingConverter.h @@ -0,0 +1,181 @@ +// +// LineEndingConverter.h +// +// Library: Foundation +// Package: Streams +// Module: LineEndingConverter +// +// Definition of the LineEndingConverter class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LineEndingConverter_INCLUDED +#define Foundation_LineEndingConverter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API LineEnding + /// This class defines valid line ending sequences + /// for InputLineEndingConverter and OutputLineEndingConverter. +{ +public: + static const std::string NEWLINE_DEFAULT; + static const std::string NEWLINE_CR; + static const std::string NEWLINE_CRLF; + static const std::string NEWLINE_LF; +}; + + +class Foundation_API LineEndingConverterStreamBuf: public UnbufferedStreamBuf + /// This stream buffer performs line ending conversion + /// on text streams. The converter can convert from and to + /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. + /// + /// Any newline sequence in the source will be replaced by the + /// target newline sequence. +{ +public: + LineEndingConverterStreamBuf(std::istream& istr); + /// Creates the LineEndingConverterStreamBuf and connects it + /// to the given input stream. + + LineEndingConverterStreamBuf(std::ostream& ostr); + /// Creates the LineEndingConverterStreamBuf and connects it + /// to the given output stream. + + ~LineEndingConverterStreamBuf(); + /// Destroys the LineEndingConverterStream. + + void setNewLine(const std::string& newLineCharacters); + /// Sets the target line ending for the converter. + /// + /// Possible values are: + /// * NEWLINE_DEFAULT (whatever is appropriate for the current platform) + /// * NEWLINE_CRLF (Windows), + /// * NEWLINE_LF (Unix), + /// * NEWLINE_CR (Macintosh) + /// + /// In theory, any character sequence can be used as newline sequence. + /// In practice, however, only the above three make sense. + + const std::string& getNewLine() const; + /// Returns the line ending currently in use. + +protected: + int readFromDevice(); + int writeToDevice(char c); + +private: + std::istream* _pIstr; + std::ostream* _pOstr; + std::string _newLine; + std::string::const_iterator _it; + char _lastChar; +}; + + +class Foundation_API LineEndingConverterIOS: public virtual std::ios + /// The base class for InputLineEndingConverter and OutputLineEndingConverter. + /// + /// This class provides common methods and is also needed to ensure + /// the correct initialization order of the stream buffer and base classes. +{ +public: + LineEndingConverterIOS(std::istream& istr); + /// Creates the LineEndingConverterIOS and connects it + /// to the given input stream. + + LineEndingConverterIOS(std::ostream& ostr); + /// Creates the LineEndingConverterIOS and connects it + /// to the given output stream. + + ~LineEndingConverterIOS(); + /// Destroys the stream. + + void setNewLine(const std::string& newLineCharacters); + /// Sets the target line ending for the converter. + /// + /// Possible values are: + /// * NEWLINE_DEFAULT (whatever is appropriate for the current platform) + /// * NEWLINE_CRLF (Windows), + /// * NEWLINE_LF (Unix), + /// * NEWLINE_CR (Macintosh) + /// + /// In theory, any character sequence can be used as newline sequence. + /// In practice, however, only the above three make sense. + /// + /// If an empty string is given, all newline characters are removed from + /// the stream. + + const std::string& getNewLine() const; + /// Returns the line ending currently in use. + + LineEndingConverterStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + LineEndingConverterStreamBuf _buf; +}; + + +class Foundation_API InputLineEndingConverter: public LineEndingConverterIOS, public std::istream + /// InputLineEndingConverter performs line ending conversion + /// on text input streams. The converter can convert from and to + /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. + /// + /// Any newline sequence in the source will be replaced by the + /// target newline sequence. +{ +public: + InputLineEndingConverter(std::istream& istr); + /// Creates the LineEndingConverterInputStream and connects it + /// to the given input stream. + + InputLineEndingConverter(std::istream& istr, const std::string& newLineCharacters); + /// Creates the LineEndingConverterInputStream and connects it + /// to the given input stream. + + ~InputLineEndingConverter(); + /// Destroys the stream. +}; + + +class Foundation_API OutputLineEndingConverter: public LineEndingConverterIOS, public std::ostream + /// OutputLineEndingConverter performs line ending conversion + /// on text output streams. The converter can convert from and to + /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. + /// + /// Any newline sequence in the source will be replaced by the + /// target newline sequence. +{ +public: + OutputLineEndingConverter(std::ostream& ostr); + /// Creates the LineEndingConverterOutputStream and connects it + /// to the given input stream. + + OutputLineEndingConverter(std::ostream& ostr, const std::string& newLineCharacters); + /// Creates the LineEndingConverterOutputStream and connects it + /// to the given input stream. + + ~OutputLineEndingConverter(); + /// Destroys the LineEndingConverterOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_LineEndingConverter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LinearHashTable.h b/contrib/libs/poco/Foundation/include/Poco/LinearHashTable.h new file mode 100644 index 0000000000..ac18b4b95a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LinearHashTable.h @@ -0,0 +1,503 @@ +// +// LinearHashTable.h +// +// Library: Foundation +// Package: Hashing +// Module: LinearHashTable +// +// Definition of the LinearHashTable class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LinearHashTable_INCLUDED +#define Foundation_LinearHashTable_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Hash.h" +#include <functional> +#include <algorithm> +#include <vector> +#include <utility> +#include <cstddef> + + +namespace Poco { + + +template <class Value, class HashFunc = Hash<Value> > +class LinearHashTable + /// This class implements a linear hash table. + /// + /// In a linear hash table, the available address space + /// grows or shrinks dynamically. A linar hash table thus + /// supports any number of insertions or deletions without + /// lookup or insertion performance deterioration. + /// + /// Linear hashing was discovered by Witold Litwin in 1980 + /// and described in the paper LINEAR HASHING: A NEW TOOL FOR FILE AND TABLE ADDRESSING. + /// + /// For more information on linear hashing, see <http://en.wikipedia.org/wiki/Linear_hash>. + /// + /// The LinearHashTable is not thread safe. + /// + /// Value must support comparison for equality. + /// + /// Find, insert and delete operations are basically O(1) with regard + /// to the total number of elements in the table, and O(N) with regard + /// to the number of elements in the bucket where the element is stored. + /// On average, every bucket stores one element; the exact number depends + /// on the quality of the hash function. In most cases, the maximum number of + /// elements in a bucket should not exceed 3. +{ +public: + typedef Value ValueType; + typedef Value& Reference; + typedef const Value& ConstReference; + typedef Value* Pointer; + typedef const Value* ConstPointer; + typedef HashFunc Hash; + typedef std::vector<Value> Bucket; + typedef std::vector<Bucket> BucketVec; + typedef typename Bucket::iterator BucketIterator; + typedef typename BucketVec::iterator BucketVecIterator; + + class ConstIterator: public std::iterator<std::forward_iterator_tag, Value> + { + public: + ConstIterator(): _initialized(false) + { + } + + ConstIterator(const BucketVecIterator& vecIt, const BucketVecIterator& endIt, const BucketIterator& buckIt): + _vecIt(vecIt), + _endIt(endIt), + _buckIt(buckIt), + _initialized(true) + { + } + + ConstIterator(const ConstIterator& it): + _vecIt(it._vecIt), + _endIt(it._endIt), + _buckIt(it._buckIt), + _initialized(it._initialized) + + { + } + + ConstIterator& operator = (const ConstIterator& it) + { + ConstIterator tmp(it); + swap(tmp); + return *this; + } + + void swap(ConstIterator& it) + { + using std::swap; + // uninitialized iterators crash when swapped + if (_initialized) + { + swap(_vecIt, it._vecIt); + swap(_endIt, it._endIt); + swap(_buckIt, it._buckIt); + swap(_initialized, it._initialized); + } + else + { + _vecIt = it._vecIt; + _endIt = it._endIt; + _buckIt = it._buckIt; + _initialized = it._initialized; + } + } + + bool operator == (const ConstIterator& it) const + { + return _vecIt == it._vecIt && (_vecIt == _endIt || _buckIt == it._buckIt); + } + + bool operator != (const ConstIterator& it) const + { + return _vecIt != it._vecIt || (_vecIt != _endIt && _buckIt != it._buckIt); + } + + const typename Bucket::value_type& operator * () const + { + return *_buckIt; + } + + const typename Bucket::value_type* operator -> () const + { + return &*_buckIt; + } + + ConstIterator& operator ++ () // prefix + { + if (_vecIt != _endIt) + { + ++_buckIt; + while (_vecIt != _endIt && _buckIt == _vecIt->end()) + { + ++_vecIt; + if (_vecIt != _endIt) _buckIt = _vecIt->begin(); + } + } + return *this; + } + + ConstIterator operator ++ (int) // postfix + { + ConstIterator tmp(*this); + ++*this; + return tmp; + } + + protected: + BucketVecIterator _vecIt; + BucketVecIterator _endIt; + BucketIterator _buckIt; + bool _initialized; + + friend class LinearHashTable; + }; + + class Iterator: public ConstIterator + { + public: + Iterator() + { + } + + Iterator(const BucketVecIterator& vecIt, const BucketVecIterator& endIt, const BucketIterator& buckIt): + ConstIterator(vecIt, endIt, buckIt) + { + } + + Iterator(const Iterator& it): + ConstIterator(it) + { + } + + Iterator& operator = (const Iterator& it) + { + Iterator tmp(it); + ConstIterator::swap(tmp); + return *this; + } + + void swap(Iterator& it) + { + ConstIterator::swap(it); + } + + typename Bucket::value_type& operator * () + { + return *this->_buckIt; + } + + const typename Bucket::value_type& operator * () const + { + return *this->_buckIt; + } + + typename Bucket::value_type* operator -> () + { + return &*this->_buckIt; + } + + const typename Bucket::value_type* operator -> () const + { + return &*this->_buckIt; + } + + Iterator& operator ++ () // prefix + { + ConstIterator::operator ++ (); + return *this; + } + + Iterator operator ++ (int) // postfix + { + Iterator tmp(*this); + ++*this; + return tmp; + } + + friend class LinearHashTable; + }; + + LinearHashTable(std::size_t initialReserve = 64): + _split(0), + _front(1), + _size(0) + /// Creates the LinearHashTable, using the given initialReserve. + { + _buckets.reserve(calcSize(initialReserve)); + _buckets.push_back(Bucket()); + } + + LinearHashTable(const LinearHashTable& table): + _buckets(table._buckets), + _split(table._split), + _front(table._front), + _size(table._size) + /// Creates the LinearHashTable by copying another one. + { + } + + ~LinearHashTable() + /// Destroys the LinearHashTable. + { + } + + LinearHashTable& operator = (const LinearHashTable& table) + /// Assigns another LinearHashTable. + { + LinearHashTable tmp(table); + swap(tmp); + return *this; + } + + void swap(LinearHashTable& table) + /// Swaps the LinearHashTable with another one. + { + using std::swap; + swap(_buckets, table._buckets); + swap(_split, table._split); + swap(_front, table._front); + swap(_size, table._size); + } + + ConstIterator begin() const + /// Returns an iterator pointing to the first entry, if one exists. + { + BucketVecIterator it(_buckets.begin()); + BucketVecIterator end(_buckets.end()); + while (it != end && it->empty()) + { + ++it; + } + if (it == end) + return this->end(); + else + return ConstIterator(it, end, it->begin()); + } + + ConstIterator end() const + /// Returns an iterator pointing to the end of the table. + { + return ConstIterator(_buckets.end(), _buckets.end(), _buckets.front().end()); + } + + Iterator begin() + /// Returns an iterator pointing to the first entry, if one exists. + { + BucketVecIterator it(_buckets.begin()); + BucketVecIterator end(_buckets.end()); + while (it != end && it->empty()) + { + ++it; + } + if (it == end) + return this->end(); + else + return Iterator(it, end, it->begin()); + } + + Iterator end() + /// Returns an iterator pointing to the end of the table. + { + return Iterator(_buckets.end(), _buckets.end(), _buckets.front().end()); + } + + ConstIterator find(const Value& value) const + /// Finds an entry in the table. + { + std::size_t addr = bucketAddress(value); + BucketVecIterator it(_buckets.begin() + addr); + BucketIterator buckIt(std::find(it->begin(), it->end(), value)); + if (buckIt != it->end()) + return ConstIterator(it, _buckets.end(), buckIt); + else + return end(); + } + + Iterator find(const Value& value) + /// Finds an entry in the table. + { + std::size_t addr = bucketAddress(value); + BucketVecIterator it(_buckets.begin() + addr); + BucketIterator buckIt(std::find(it->begin(), it->end(), value)); + if (buckIt != it->end()) + return Iterator(it, _buckets.end(), buckIt); + else + return end(); + } + + std::size_t count(const Value& value) const + /// Returns the number of elements with the given + /// value, with is either 1 or 0. + { + return find(value) != end() ? 1 : 0; + } + + std::pair<Iterator, bool> insert(const Value& value) + /// Inserts an element into the table. + /// + /// If the element already exists in the table, + /// a pair(iterator, false) with iterator pointing to the + /// existing element is returned. + /// Otherwise, the element is inserted an a + /// pair(iterator, true) with iterator + /// pointing to the new element is returned. + { + std::size_t hash = _hash(value); + std::size_t addr = bucketAddressForHash(hash); + BucketVecIterator it(_buckets.begin() + addr); + BucketIterator buckIt(std::find(it->begin(), it->end(), value)); + if (buckIt == it->end()) + { + split(); + addr = bucketAddressForHash(hash); + it = _buckets.begin() + addr; + buckIt = it->insert(it->end(), value); + ++_size; + return std::make_pair(Iterator(it, _buckets.end(), buckIt), true); + } + else + { + return std::make_pair(Iterator(it, _buckets.end(), buckIt), false); + } + } + + void erase(Iterator it) + /// Erases the element pointed to by it. + { + if (it != end()) + { + it._vecIt->erase(it._buckIt); + --_size; + merge(); + } + } + + void erase(const Value& value) + /// Erases the element with the given value, if it exists. + { + Iterator it = find(value); + erase(it); + } + + void clear() + /// Erases all elements. + { + LinearHashTable empty; + swap(empty); + } + + std::size_t size() const + /// Returns the number of elements in the table. + { + return _size; + } + + bool empty() const + /// Returns true iff the table is empty. + { + return _size == 0; + } + + std::size_t buckets() const + /// Returns the number of allocated buckets. + { + return _buckets.size(); + } + +protected: + std::size_t bucketAddress(const Value& value) const + { + std::size_t n = _hash(value); + if (n % _front >= _split) + return n % _front; + else + return n % (2*_front); + } + + std::size_t bucketAddressForHash(std::size_t hash) + { + if (hash % _front >= _split) + return hash % _front; + else + return hash % (2*_front); + } + + void split() + { + if (_split == _front) + { + _split = 0; + _front *= 2; + _buckets.reserve(_front*2); + } + Bucket tmp; + _buckets.push_back(tmp); + _buckets[_split].swap(tmp); + ++_split; + for (BucketIterator it = tmp.begin(); it != tmp.end(); ++it) + { + using std::swap; + std::size_t addr = bucketAddress(*it); + _buckets[addr].push_back(Value()); + swap(*it, _buckets[addr].back()); + } + } + + void merge() + { + if (_split == 0) + { + _front /= 2; + _split = _front; + } + --_split; + Bucket tmp; + tmp.swap(_buckets.back()); + _buckets.pop_back(); + for (BucketIterator it = tmp.begin(); it != tmp.end(); ++it) + { + using std::swap; + std::size_t addr = bucketAddress(*it); + _buckets[addr].push_back(Value()); + swap(*it, _buckets[addr].back()); + } + } + + static std::size_t calcSize(std::size_t initialSize) + { + std::size_t size = 32; + while (size < initialSize) size *= 2; + return size; + } + +private: + // Evil hack: _buckets must be mutable because both ConstIterator and Iterator hold + // ordinary iterator's (not const_iterator's). + mutable BucketVec _buckets; + std::size_t _split; + std::size_t _front; + std::size_t _size; + HashFunc _hash; +}; + + +} // namespace Poco + + +#endif // Foundation_LinearHashTable_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ListMap.h b/contrib/libs/poco/Foundation/include/Poco/ListMap.h new file mode 100644 index 0000000000..03c056d810 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ListMap.h @@ -0,0 +1,246 @@ +// +// ListMap.h +// +// Library: Foundation +// Package: Hashing +// Module: ListMap +// +// Definition of the ListMap class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ListMap_INCLUDED +#define Foundation_ListMap_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/String.h" +#include "Poco/Exception.h" +#include <list> +#include <utility> + + +namespace Poco { + + +template <class Key, class Mapped, class Container = std::list<std::pair<Key, Mapped> >, bool CaseSensitive = false > +class ListMap + /// This class implements a multimap in terms of a sequential container. + /// The use for this type of associative container is wherever automatic + /// ordering of elements is not desirable. Naturally, this container will + /// have inferior data retrieval performance and it is not recommended for + /// use with large datasets. The main purpose within POCO is for Internet + /// messages (email message, http headers etc), to prevent automatic + /// header entry reordering. +{ +public: + typedef Key KeyType; + typedef Mapped MappedType; + typedef Mapped& Reference; + typedef const Mapped& ConstReference; + typedef Mapped* Pointer; + typedef const Mapped* ConstPointer; + + typedef typename Container::value_type ValueType; + typedef typename Container::size_type SizeType; + typedef typename Container::iterator Iterator; + typedef typename Container::const_iterator ConstIterator; + + ListMap() + /// Creates an empty ListMap. + { + } + + ListMap(std::size_t initialReserve): + _list(initialReserve) + /// Creates the ListMap with room for initialReserve entries. + { + } + + ListMap& operator = (const ListMap& map) + /// Assigns another ListMap. + { + ListMap tmp(map); + swap(tmp); + return *this; + } + + void swap(ListMap& map) + /// Swaps the ListMap with another one. + { + _list.swap(map._list); + } + + ConstIterator begin() const + /// Returns the beginning of the map. + { + return _list.begin(); + } + + ConstIterator end() const + /// Returns the end of the map. + { + return _list.end(); + } + + Iterator begin() + /// Returns the beginning of the map. + { + return _list.begin(); + } + + Iterator end() + /// Returns the end of the map. + { + return _list.end(); + } + + ConstIterator find(const KeyType& key) const + /// Finds the first occurrence of the key and + /// returns iterator pointing to the found entry + /// or iterator pointing to the end if entry is + /// not found. + { + typename Container::const_iterator it = _list.begin(); + typename Container::const_iterator itEnd = _list.end(); + for(; it != itEnd; ++it) + { + if (isEqual(it->first, key)) return it; + } + return itEnd; + } + + Iterator find(const KeyType& key) + /// Finds the first occurrence of the key and + /// returns iterator pointing to the found entry + /// or iterator pointing to the end if entry is + /// not found. + { + typename Container::iterator it = _list.begin(); + typename Container::iterator itEnd = _list.end(); + for(; it != itEnd; ++it) + { + if (isEqual(it->first, key)) return it; + } + return itEnd; + } + + Iterator insert(const ValueType& val) + /// Inserts the value into the map. If one or more values + /// already exist, new value is inserted at the end of the + /// block. Thus, all the equal value entries are located + /// sequentially at all times. + /// Returns iterator pointing to the newly inserted value + { + Iterator it = find(val.first); + while (it != _list.end() && isEqual(it->first, val.first)) ++it; + return _list.insert(it, val); + } + + void erase(Iterator it) + { + _list.erase(it); + } + + SizeType erase(const KeyType& key) + { + SizeType count = 0; + Iterator it = find(key); + bool removed = false; + while (it != _list.end()) + { + if (isEqual(it->first, key)) + { + ++count; + it = _list.erase(it); + removed = true; + } + else + { + if (removed) return count; + ++it; + } + } + return count; + } + + void clear() + { + _list.clear(); + } + + std::size_t size() const + { + return _list.size(); + } + + bool empty() const + { + return _list.empty(); + } + + ConstReference operator [] (const KeyType& key) const + { + ConstIterator it = find(key); + if (it != _list.end()) + return it->second; + else + throw NotFoundException(); + } + + Reference operator [] (const KeyType& key) + { + Iterator it = find(key); + if (it != _list.end()) + return it->second; + else + { + ValueType value(key, Mapped()); + Iterator itInsert = insert(value); + return itInsert->second; + } + } + +private: + template <typename T1, typename T2> + bool isEqual(T1 val1, T2 val2) const + { + return val1 == val2; + } + + bool isEqual(const std::string& s1, const std::string& s2) const + { + if (!CaseSensitive) + return Poco::icompare(s1, s2) == 0; + else + return s1 == s2; + } + + bool isEqual(const std::string& s1, const char* s2) const + { + return isEqual(s1, std::string(s2)); + } + + bool isEqual(const char* s1, const std::string& s2) const + { + return isEqual(std::string(s1), s2); + } + + bool isEqual(const char* s1, const char* s2) const + { + return isEqual(std::string(s1), std::string(s2)); + } + + Container _list; +}; + + +} // namespace Poco + + +#endif // Foundation_ListMap_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LocalDateTime.h b/contrib/libs/poco/Foundation/include/Poco/LocalDateTime.h new file mode 100644 index 0000000000..08c90b6582 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LocalDateTime.h @@ -0,0 +1,388 @@ +// +// LocalDateTime.h +// +// Library: Foundation +// Package: DateTime +// Module: LocalDateTime +// +// Definition of the LocalDateTime class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LocalDateTime_INCLUDED +#define Foundation_LocalDateTime_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DateTime.h" + + +namespace Poco { + + +class Foundation_API LocalDateTime + /// This class represents an instant in local time + /// (as opposed to UTC), expressed in years, months, days, + /// hours, minutes, seconds and milliseconds based on the + /// Gregorian calendar. + /// + /// In addition to the date and time, the class also + /// maintains a time zone differential, which denotes + /// the difference in seconds from UTC to local time, + /// i.e. UTC = local time - time zone differential. + /// + /// Although LocalDateTime supports relational and arithmetic + /// operators, all date/time comparisons and date/time arithmetics + /// should be done in UTC, using the DateTime or Timestamp + /// class for better performance. The relational operators + /// normalize the dates/times involved to UTC before carrying out + /// the comparison. + /// + /// The time zone differential is based on the input date and + /// time and current time zone. A number of constructors accept + /// an explicit time zone differential parameter. These should + /// not be used since daylight savings time processing is impossible + /// since the time zone is unknown. Each of the constructors + /// accepting a tzd parameter have been marked as deprecated and + /// may be removed in a future revision. +{ +public: + LocalDateTime(); + /// Creates a LocalDateTime with the current date/time + /// for the current time zone. + + LocalDateTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); + /// Creates a LocalDateTime for the given Gregorian local date and time. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 60 (allowing leap seconds). + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + //@ deprecated + LocalDateTime(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond); + /// Creates a LocalDateTime for the given Gregorian date and time in the + /// time zone denoted by the time zone differential in tzd. + /// * tzd is in seconds. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 60 (allowing leap seconds). + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + LocalDateTime(const DateTime& dateTime); + /// Creates a LocalDateTime from the UTC time given in dateTime, + /// using the time zone differential of the current time zone. + + //@ deprecated + LocalDateTime(int tzd, const DateTime& dateTime); + /// Creates a LocalDateTime from the UTC time given in dateTime, + /// using the given time zone differential. Adjusts dateTime + /// for the given time zone differential. + + //@ deprecated + LocalDateTime(int tzd, const DateTime& dateTime, bool adjust); + /// Creates a LocalDateTime from the UTC time given in dateTime, + /// using the given time zone differential. If adjust is true, + /// adjusts dateTime for the given time zone differential. + + LocalDateTime(double julianDay); + /// Creates a LocalDateTime for the given Julian day in the local time zone. + + //@ deprecated + LocalDateTime(int tzd, double julianDay); + /// Creates a LocalDateTime for the given Julian day in the time zone + /// denoted by the time zone differential in tzd. + + LocalDateTime(const LocalDateTime& dateTime); + /// Copy constructor. Creates the LocalDateTime from another one. + + ~LocalDateTime(); + /// Destroys the LocalDateTime. + + LocalDateTime& operator = (const LocalDateTime& dateTime); + /// Assigns another LocalDateTime. + + LocalDateTime& operator = (const Timestamp& timestamp); + /// Assigns a timestamp + + LocalDateTime& operator = (double julianDay); + /// Assigns a Julian day in the local time zone. + + LocalDateTime& assign(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microseconds = 0); + /// Assigns a Gregorian local date and time. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 60 (allowing leap seconds). + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + //@ deprecated + LocalDateTime& assign(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds); + /// Assigns a Gregorian local date and time in the time zone denoted by + /// the time zone differential in tzd. + /// * tzd is in seconds. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 60 (allowing leap seconds). + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + //@ deprecated + LocalDateTime& assign(int tzd, double julianDay); + /// Assigns a Julian day in the time zone denoted by the + /// time zone differential in tzd. + + void swap(LocalDateTime& dateTime); + /// Swaps the LocalDateTime with another one. + + int year() const; + /// Returns the year. + + int month() const; + /// Returns the month (1 to 12). + + int week(int firstDayOfWeek = DateTime::MONDAY) const; + /// Returns the week number within the year. + /// FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). + /// The returned week number will be from 0 to 53. Week number 1 is the week + /// containing January 4. This is in accordance to ISO 8601. + /// + /// The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started + /// on a Saturday, week 1 will be the week starting on Monday, January 3. + /// January 1 and 2 will fall within week 0 (or the last week of the previous year). + /// + /// For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1. + /// There will be no week 0 in 2007. + + int day() const; + /// Returns the day witin the month (1 to 31). + + int dayOfWeek() const; + /// Returns the weekday (0 to 6, where + /// 0 = Sunday, 1 = Monday, ..., 6 = Saturday). + + int dayOfYear() const; + /// Returns the number of the day in the year. + /// January 1 is 1, February 1 is 32, etc. + + int hour() const; + /// Returns the hour (0 to 23). + + int hourAMPM() const; + /// Returns the hour (0 to 12). + + bool isAM() const; + /// Returns true if hour < 12; + + bool isPM() const; + /// Returns true if hour >= 12. + + int minute() const; + /// Returns the minute (0 to 59). + + int second() const; + /// Returns the second (0 to 59). + + int millisecond() const; + /// Returns the millisecond (0 to 999) + + int microsecond() const; + /// Returns the microsecond (0 to 999) + + double julianDay() const; + /// Returns the julian day for the date. + + int tzd() const; + /// Returns the time zone differential. + + DateTime utc() const; + /// Returns the UTC equivalent for the local date and time. + + Timestamp timestamp() const; + /// Returns the date and time expressed as a Timestamp. + + Timestamp::UtcTimeVal utcTime() const; + /// Returns the UTC equivalent for the local date and time. + + bool operator == (const LocalDateTime& dateTime) const; + bool operator != (const LocalDateTime& dateTime) const; + bool operator < (const LocalDateTime& dateTime) const; + bool operator <= (const LocalDateTime& dateTime) const; + bool operator > (const LocalDateTime& dateTime) const; + bool operator >= (const LocalDateTime& dateTime) const; + + LocalDateTime operator + (const Timespan& span) const; + LocalDateTime operator - (const Timespan& span) const; + Timespan operator - (const LocalDateTime& dateTime) const; + LocalDateTime& operator += (const Timespan& span); + LocalDateTime& operator -= (const Timespan& span); + +protected: + LocalDateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff, int tzd); + + void determineTzd(bool adjust = false); + /// Recalculate the tzd based on the _dateTime member based + /// on the current timezone using the Standard C runtime functions. + /// If adjust is true, then adjustForTzd() is called after the + /// differential is calculated. + + void adjustForTzd(); + /// Adjust the _dateTime member based on the _tzd member. + + std::time_t dstOffset(int& dstOffset) const; + /// Determine the DST offset for the current date/time. + +private: + DateTime _dateTime; + int _tzd; + + friend class DateTimeFormatter; + friend class DateTimeParser; +}; + + +// +// inlines +// +inline int LocalDateTime::year() const +{ + return _dateTime.year(); +} + + +inline int LocalDateTime::month() const +{ + return _dateTime.month(); +} + + +inline int LocalDateTime::week(int firstDayOfWeek) const +{ + return _dateTime.week(firstDayOfWeek); +} + + +inline int LocalDateTime::day() const +{ + return _dateTime.day(); +} + + +inline int LocalDateTime::dayOfWeek() const +{ + return _dateTime.dayOfWeek(); +} + + +inline int LocalDateTime::dayOfYear() const +{ + return _dateTime.dayOfYear(); +} + + +inline int LocalDateTime::hour() const +{ + return _dateTime.hour(); +} + + +inline int LocalDateTime::hourAMPM() const +{ + return _dateTime.hourAMPM(); +} + + +inline bool LocalDateTime::isAM() const +{ + return _dateTime.isAM(); +} + + +inline bool LocalDateTime::isPM() const +{ + return _dateTime.isPM(); +} + + +inline int LocalDateTime::minute() const +{ + return _dateTime.minute(); +} + + +inline int LocalDateTime::second() const +{ + return _dateTime.second(); +} + + +inline int LocalDateTime::millisecond() const +{ + return _dateTime.millisecond(); +} + + +inline int LocalDateTime::microsecond() const +{ + return _dateTime.microsecond(); +} + + +inline double LocalDateTime::julianDay() const +{ + return _dateTime.julianDay(); +} + + +inline int LocalDateTime::tzd() const +{ + return _tzd; +} + + +inline Timestamp LocalDateTime::timestamp() const +{ + return Timestamp::fromUtcTime(_dateTime.utcTime()); +} + + +inline Timestamp::UtcTimeVal LocalDateTime::utcTime() const +{ + return _dateTime.utcTime() - ((Timestamp::TimeDiff) _tzd)*10000000; +} + + +inline void LocalDateTime::adjustForTzd() +{ + _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); +} + + +inline void swap(LocalDateTime& d1, LocalDateTime& d2) +{ + d1.swap(d2); +} + + +} // namespace Poco + + +#endif // Foundation_LocalDateTime_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LogFile.h b/contrib/libs/poco/Foundation/include/Poco/LogFile.h new file mode 100644 index 0000000000..37872b5350 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LogFile.h @@ -0,0 +1,93 @@ +// +// LogFile.h +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFile class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LogFile_INCLUDED +#define Foundation_LogFile_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/LogFile_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/LogFile_WIN32.h" +#else +#include "Poco/LogFile_STD.h" +#endif + + +namespace Poco { + + +class Foundation_API LogFile: public LogFileImpl + /// This class is used by FileChannel to work + /// with a log file. +{ +public: + LogFile(const std::string& path); + /// Creates the LogFile. + + ~LogFile(); + /// Destroys the LogFile. + + void write(const std::string& text, bool flush = true); + /// Writes the given text to the log file. + /// If flush is true, the text will be immediately + /// flushed to the file. + + UInt64 size() const; + /// Returns the current size in bytes of the log file. + + Timestamp creationDate() const; + /// Returns the date and time the log file was created. + + const std::string& path() const; + /// Returns the path given in the constructor. +}; + + +// +// inlines +// +inline void LogFile::write(const std::string& text, bool flush) +{ + writeImpl(text, flush); +} + + +inline UInt64 LogFile::size() const +{ + return sizeImpl(); +} + + +inline Timestamp LogFile::creationDate() const +{ + return creationDateImpl(); +} + + +inline const std::string& LogFile::path() const +{ + return pathImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_LogFile_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LogFile_STD.h b/contrib/libs/poco/Foundation/include/Poco/LogFile_STD.h new file mode 100644 index 0000000000..0e8feda2b3 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LogFile_STD.h @@ -0,0 +1,52 @@ +// +// LogFile_STD.h +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFileImpl class using iostreams. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LogFile_STD_INCLUDED +#define Foundation_LogFile_STD_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include "Poco/FileStream.h" + + +namespace Poco { + + +class Foundation_API LogFileImpl + /// The implementation of LogFile for non-Windows platforms. + /// The native filesystem APIs are used for + /// total control over locking behavior. +{ +public: + LogFileImpl(const std::string& path); + ~LogFileImpl(); + void writeImpl(const std::string& text, bool flush); + UInt64 sizeImpl() const; + Timestamp creationDateImpl() const; + const std::string& pathImpl() const; + +private: + std::string _path; + mutable Poco::FileOutputStream _str; + Timestamp _creationDate; +}; + + +} // namespace Poco + + +#endif // Foundation_LogFile_STD_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LogFile_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/LogFile_WIN32.h new file mode 100644 index 0000000000..ce2ff6cb0b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LogFile_WIN32.h @@ -0,0 +1,54 @@ +// +// LogFile_WIN32.h +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFileImpl class using the Windows file APIs. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LogFile_WIN32_INCLUDED +#define Foundation_LogFile_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API LogFileImpl + /// The implementation of LogFile for Windows. + /// The native filesystem APIs are used for + /// total control over locking behavior. +{ +public: + LogFileImpl(const std::string& path); + ~LogFileImpl(); + void writeImpl(const std::string& text, bool flush); + UInt64 sizeImpl() const; + Timestamp creationDateImpl() const; + const std::string& pathImpl() const; + +private: + void createFile(); + + std::string _path; + HANDLE _hFile; + Timestamp _creationDate; +}; + + +} // namespace Poco + + +#endif // Foundation_LogFile_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LogFile_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/LogFile_WIN32U.h new file mode 100644 index 0000000000..ed558a7da7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LogFile_WIN32U.h @@ -0,0 +1,54 @@ +// +// LogFile_WIN32U.h +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFileImpl class using the Windows file APIs. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LogFile_WIN32U_INCLUDED +#define Foundation_LogFile_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API LogFileImpl + /// The implementation of LogFile for Windows. + /// The native filesystem APIs are used for + /// total control over locking behavior. +{ +public: + LogFileImpl(const std::string& path); + ~LogFileImpl(); + void writeImpl(const std::string& text, bool flush); + UInt64 sizeImpl() const; + Timestamp creationDateImpl() const; + const std::string& pathImpl() const; + +private: + void createFile(); + + std::string _path; + HANDLE _hFile; + Timestamp _creationDate; +}; + + +} // namespace Poco + + +#endif // Foundation_LogFile_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LogStream.h b/contrib/libs/poco/Foundation/include/Poco/LogStream.h new file mode 100644 index 0000000000..c3d3f0850a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LogStream.h @@ -0,0 +1,192 @@ +// +// LogStream.h +// +// Library: Foundation +// Package: Logging +// Module: LogStream +// +// Definition of the LogStream class. +// +// Copyright (c) 2006-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LogStream_INCLUDED +#define Foundation_LogStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Logger.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <istream> + + +namespace Poco { + + +class Foundation_API LogStreamBuf: public UnbufferedStreamBuf + /// This class implements a streambuf interface + /// to a Logger. + /// + /// The streambuf appends all characters written to it + /// to a string. As soon as a CR or LF (std::endl) is written, + /// the string is sent to the Logger, with the set + /// priority. +{ +public: + LogStreamBuf(Logger& logger, Message::Priority priority); + /// Creates the LogStream. + + ~LogStreamBuf(); + /// Destroys the LogStream. + + void setPriority(Message::Priority priority); + /// Sets the priority for log messages. + + Message::Priority getPriority() const; + /// Returns the priority for log messages. + + Logger& logger() const; + /// Returns a reference to the Logger. + +private: + int writeToDevice(char c); + +private: + Logger& _logger; + Message::Priority _priority; + std::string _message; +}; + + +class Foundation_API LogIOS: public virtual std::ios + /// The base class for LogStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + LogIOS(Logger& logger, Message::Priority priority); + ~LogIOS(); + LogStreamBuf* rdbuf(); + +protected: + LogStreamBuf _buf; +}; + + +class Foundation_API LogStream: public LogIOS, public std::ostream + /// This class implements an ostream interface + /// to a Logger. + /// + /// The stream's buffer appends all characters written to it + /// to a string. As soon as a CR or LF (std::endl) is written, + /// the string is sent to the Logger, with the current + /// priority. + /// + /// Usage example: + /// LogStream ls(someLogger); + /// ls << "Some informational message" << std::endl; + /// ls.error() << "Some error message" << std::endl; +{ +public: + LogStream(Logger& logger, Message::Priority priority = Message::PRIO_INFORMATION); + /// Creates the LogStream, using the given logger and priority. + + LogStream(const std::string& loggerName, Message::Priority priority = Message::PRIO_INFORMATION); + /// Creates the LogStream, using the logger identified + /// by loggerName, and sets the priority. + + ~LogStream(); + /// Destroys the LogStream. + + LogStream& fatal(); + /// Sets the priority for log messages to Message::PRIO_FATAL. + + LogStream& fatal(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_FATAL + /// and writes the given message. + + LogStream& critical(); + /// Sets the priority for log messages to Message::PRIO_CRITICAL. + + LogStream& critical(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_CRITICAL + /// and writes the given message. + + LogStream& error(); + /// Sets the priority for log messages to Message::PRIO_ERROR. + + LogStream& error(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_ERROR + /// and writes the given message. + + LogStream& warning(); + /// Sets the priority for log messages to Message::PRIO_WARNING. + + LogStream& warning(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_WARNING + /// and writes the given message. + + LogStream& notice(); + /// Sets the priority for log messages to Message::PRIO_NOTICE. + + LogStream& notice(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_NOTICE + /// and writes the given message. + + LogStream& information(); + /// Sets the priority for log messages to Message::PRIO_INFORMATION. + + LogStream& information(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_INFORMATION + /// and writes the given message. + + LogStream& debug(); + /// Sets the priority for log messages to Message::PRIO_DEBUG. + + LogStream& debug(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_DEBUG + /// and writes the given message. + + LogStream& trace(); + /// Sets the priority for log messages to Message::PRIO_TRACE. + + LogStream& trace(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_TRACE + /// and writes the given message. + + LogStream& test(); + /// Sets the priority for log messages to Message::PRIO_TEST. + + LogStream& test(const std::string& message); + /// Sets the priority for log messages to Message::PRIO_TEST + /// and writes the given message. + + LogStream& priority(Message::Priority priority); + /// Sets the priority for log messages. +}; + + +// +// inlines +// +inline Message::Priority LogStreamBuf::getPriority() const +{ + return _priority; +} + + +inline Logger& LogStreamBuf::logger() const +{ + return _logger; +} + + +} // namespace Poco + + +#endif // Foundation_LogStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Logger.h b/contrib/libs/poco/Foundation/include/Poco/Logger.h new file mode 100644 index 0000000000..8dbf8327c8 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Logger.h @@ -0,0 +1,1447 @@ +// +// Logger.h +// +// Library: Foundation +// Package: Logging +// Module: Logger +// +// Definition of the Logger class. +// +// Copyright (c) 2004-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Logger_INCLUDED +#define Foundation_Logger_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Message.h" +#include "Poco/Format.h" +#include <map> +#include <vector> +#include <cstddef> +#include <atomic> + + +namespace Poco { + + +class Exception; + + +class Foundation_API Logger: public Channel + /// Logger is a special Channel that acts as the main + /// entry point into the logging framework. + /// + /// An application uses instances of the Logger class to generate its log messages + /// and send them on their way to their final destination. Logger instances + /// are organized in a hierarchical, tree-like manner and are maintained by + /// the framework. Every Logger object has exactly one direct ancestor, with + /// the exception of the root logger. A newly created logger inherits its properties - + /// channel and level - from its direct ancestor. Every logger is connected + /// to a channel, to which it passes on its messages. Furthermore, every logger + /// has a log level, which is used for filtering messages based on their priority. + /// Only messages with a priority equal to or higher than the specified level + /// are passed on. For example, if the level of a logger is set to three (PRIO_ERROR), + /// only messages with priority PRIO_ERROR, PRIO_CRITICAL and PRIO_FATAL will + /// propagate. If the level is set to zero, the logger is effectively disabled. + /// + /// The name of a logger determines the logger's place within the logger hierarchy. + /// The name of the root logger is always "", the empty string. For all other + /// loggers, the name is made up of one or more components, separated by a period. + /// For example, the loggers with the name HTTPServer.RequestHandler and HTTPServer.Listener + /// are descendants of the logger HTTPServer, which itself is a descendant of + /// the root logger. There is not limit as to how deep + /// the logger hierarchy can become. Once a logger has been created and it has + /// inherited the channel and level from its ancestor, it loses the connection + /// to it. So changes to the level or channel of a logger do not affect its + /// descendants. This greatly simplifies the implementation of the framework + /// and is no real restriction, because almost always levels and channels are + /// set up at application startup and never changed afterwards. Nevertheless, + /// there are methods to simultaneously change the level and channel of all + /// loggers in a certain hierarchy. + /// + /// There are also convenience macros available that wrap the actual + /// logging statement into a check whether the Logger's log level + /// is sufficient to actually log the message. This allows to increase + /// the application performance if many complex log statements + /// are used. The macros also add the source file path and line + /// number into the log message so that it is available to formatters. + /// Variants of these macros that allow message formatting with Poco::format() + /// are also available. Up to four arguments are supported. + /// + /// Examples: + /// poco_warning(logger, "This is a warning"); + /// poco_information_f2(logger, "An informational message with args: %d, %d", 1, 2); +{ +public: + const std::string& name() const; + /// Returns the name of the logger, which is set as the + /// message source on all messages created by the logger. + + void setChannel(Channel* pChannel); + /// Attaches the given Channel to the Logger. + + Channel* getChannel() const; + /// Returns the Channel attached to the logger. + + void setLevel(int level); + /// Sets the Logger's log level. + /// + /// See Message::Priority for valid log levels. + /// Setting the log level to zero turns off + /// logging for that Logger. + + int getLevel() const; + /// Returns the Logger's log level. + + void setLevel(const std::string& level); + /// Sets the Logger's log level using a symbolic value. + /// + /// Valid values are: + /// - none (turns off logging) + /// - fatal + /// - critical + /// - error + /// - warning + /// - notice + /// - information + /// - debug + /// - trace + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// Only the "channel" and "level" properties are supported, which allow + /// setting the target channel and log level, respectively, via the LoggingRegistry. + /// The "channel" and "level" properties are set-only. + + void log(const Message& msg); + /// Logs the given message if its priority is + /// greater than or equal to the Logger's log level. + + void log(const Exception& exc); + /// Logs the given exception with priority PRIO_ERROR. + + void log(const Exception& exc, const char* file, int line); + /// Logs the given exception with priority PRIO_ERROR. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void fatal(const std::string& msg); + /// If the Logger's log level is at least PRIO_FATAL, + /// creates a Message with priority PRIO_FATAL + /// and the given message text and sends it + /// to the attached channel. + + void fatal(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_FATAL, + /// creates a Message with priority PRIO_FATAL + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void fatal(const std::string& fmt, const Any& value1); + void fatal(const std::string& fmt, const Any& value1, const Any& value2); + void fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + void critical(const std::string& msg); + /// If the Logger's log level is at least PRIO_CRITICAL, + /// creates a Message with priority PRIO_CRITICAL + /// and the given message text and sends it + /// to the attached channel. + + void critical(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_CRITICAL, + /// creates a Message with priority PRIO_CRITICAL + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void critical(const std::string& fmt, const Any& value1); + void critical(const std::string& fmt, const Any& value1, const Any& value2); + void critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + void error(const std::string& msg); + /// If the Logger's log level is at least PRIO_ERROR, + /// creates a Message with priority PRIO_ERROR + /// and the given message text and sends it + /// to the attached channel. + + void error(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_ERROR, + /// creates a Message with priority PRIO_ERROR + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void error(const std::string& fmt, const Any& value1); + void error(const std::string& fmt, const Any& value1, const Any& value2); + void error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + void warning(const std::string& msg); + /// If the Logger's log level is at least PRIO_WARNING, + /// creates a Message with priority PRIO_WARNING + /// and the given message text and sends it + /// to the attached channel. + + void warning(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_WARNING, + /// creates a Message with priority PRIO_WARNING + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void warning(const std::string& fmt, const Any& value1); + void warning(const std::string& fmt, const Any& value1, const Any& value2); + void warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + void notice(const std::string& msg); + /// If the Logger's log level is at least PRIO_NOTICE, + /// creates a Message with priority PRIO_NOTICE + /// and the given message text and sends it + /// to the attached channel. + + void notice(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_NOTICE, + /// creates a Message with priority PRIO_NOTICE + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void notice(const std::string& fmt, const Any& value1); + void notice(const std::string& fmt, const Any& value1, const Any& value2); + void notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + void information(const std::string& msg); + /// If the Logger's log level is at least PRIO_INFORMATION, + /// creates a Message with priority PRIO_INFORMATION + /// and the given message text and sends it + /// to the attached channel. + + void information(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_INFORMATION, + /// creates a Message with priority PRIO_INFORMATION + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void information(const std::string& fmt, const Any& value1); + void information(const std::string& fmt, const Any& value1, const Any& value2); + void information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + void debug(const std::string& msg); + /// If the Logger's log level is at least PRIO_DEBUG, + /// creates a Message with priority PRIO_DEBUG + /// and the given message text and sends it + /// to the attached channel. + + void debug(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_DEBUG, + /// creates a Message with priority PRIO_DEBUG + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void debug(const std::string& fmt, const Any& value1); + void debug(const std::string& fmt, const Any& value1, const Any& value2); + void debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + void trace(const std::string& msg); + /// If the Logger's log level is at least PRIO_TRACE, + /// creates a Message with priority PRIO_TRACE + /// and the given message text and sends it + /// to the attached channel. + + void trace(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_TRACE, + /// creates a Message with priority PRIO_TRACE + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void trace(const std::string& fmt, const Any& value1); + void trace(const std::string& fmt, const Any& value1, const Any& value2); + void trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + void test(const std::string& msg); + /// If the Logger's log level is at least PRIO_TEST, + /// creates a Message with priority PRIO_TEST + /// and the given message text and sends it + /// to the attached channel. + + void test(const std::string& msg, const char* file, int line); + /// If the Logger's log level is at least PRIO_TEST, + /// creates a Message with priority PRIO_TEST + /// and the given message text and sends it + /// to the attached channel. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + void test(const std::string& fmt, const Any& value1); + void test(const std::string& fmt, const Any& value1, const Any& value2); + void test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); + void test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); + void test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); + void test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + void test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7); + void test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8); + void test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9); + void test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10); + + + void dump(const std::string& msg, const void* buffer, std::size_t length, Message::Priority prio = Message::PRIO_DEBUG); + /// Logs the given message, followed by the data in buffer. + /// + /// The data in buffer is written in canonical hex+ASCII form: + /// Offset (4 bytes) in hexadecimal, followed by sixteen + /// space-separated, two column, hexadecimal bytes, + /// followed by the same sixteen bytes as ASCII characters. + /// For bytes outside the range 32 .. 127, a dot is printed. + + bool is(int level) const; + /// Returns true if at least the given log level is set. + + bool fatal() const; + /// Returns true if the log level is at least PRIO_FATAL. + + bool critical() const; + /// Returns true if the log level is at least PRIO_CRITICAL. + + bool error() const; + /// Returns true if the log level is at least PRIO_ERROR. + + bool warning() const; + /// Returns true if the log level is at least PRIO_WARNING. + + bool notice() const; + /// Returns true if the log level is at least PRIO_NOTICE. + + bool information() const; + /// Returns true if the log level is at least PRIO_INFORMATION. + + bool debug() const; + /// Returns true if the log level is at least PRIO_DEBUG. + + bool trace() const; + /// Returns true if the log level is at least PRIO_TRACE. + + bool test() const; + /// Returns true if the log level is at least PRIO_TEST. + + static std::string format(const std::string& fmt, const std::string& arg); + /// Replaces all occurences of $0 in fmt with the string given in arg and + /// returns the result. To include a dollar sign in the result string, + /// specify two dollar signs ($$) in the format string. + + static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1); + /// Replaces all occurences of $<n> in fmt with the string given in arg<n> and + /// returns the result. To include a dollar sign in the result string, + /// specify two dollar signs ($$) in the format string. + + static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2); + /// Replaces all occurences of $<n> in fmt with the string given in arg<n> and + /// returns the result. To include a dollar sign in the result string, + /// specify two dollar signs ($$) in the format string. + + static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2, const std::string& arg3); + /// Replaces all occurences of $<n> in fmt with the string given in arg<n> and + /// returns the result. To include a dollar sign in the result string, + /// specify two dollar signs ($$) in the format string. + + static void formatDump(std::string& message, const void* buffer, std::size_t length); + /// Creates a hex-dump of the given buffer and appends it to the + /// given message string. + + static void setLevel(const std::string& name, int level); + /// Sets the given log level on all loggers that are + /// descendants of the Logger with the given name. + + static void setChannel(const std::string& name, Channel* pChannel); + /// Attaches the given Channel to all loggers that are + /// descendants of the Logger with the given name. + + static void setProperty(const std::string& loggerName, const std::string& propertyName, const std::string& value); + /// Sets or changes a configuration property for all loggers + /// that are descendants of the Logger with the given name. + + static Logger& get(const std::string& name); + /// Returns a reference to the Logger with the given name. + /// If the Logger does not yet exist, it is created, based + /// on its parent logger. + + static Logger& unsafeGet(const std::string& name); + /// Returns a reference to the Logger with the given name. + /// If the Logger does not yet exist, it is created, based + /// on its parent logger. + /// + /// WARNING: This method is not thread safe. You should + /// probably use get() instead. + /// The only time this method should be used is during + /// program initialization, when only one thread is running. + + static Logger& create(const std::string& name, Channel* pChannel, int level = Message::PRIO_INFORMATION); + /// Creates and returns a reference to a Logger with the + /// given name. The Logger's Channel and log level as set as + /// specified. + + static Logger& root(); + /// Returns a reference to the root logger, which is the ultimate + /// ancestor of all Loggers. + + static Logger* has(const std::string& name); + /// Returns a pointer to the Logger with the given name if it + /// exists, or a null pointer otherwse. + + static void destroy(const std::string& name); + /// Destroys the logger with the specified name. Does nothing + /// if the logger is not found. + /// + /// After a logger has been destroyed, all references to it + /// become invalid. + + static void shutdown(); + /// Shuts down the logging framework and releases all + /// Loggers. + + static void names(std::vector<std::string>& names); + /// Fills the given vector with the names + /// of all currently defined loggers. + + static int parseLevel(const std::string& level); + /// Parses a symbolic log level from a string and + /// returns the resulting numeric level. + /// + /// Valid symbolic levels are: + /// - none (turns off logging) + /// - fatal + /// - critical + /// - error + /// - warning + /// - notice + /// - information + /// - debug + /// - trace + /// - test + /// + /// The level is not case sensitive. + + static const std::string ROOT; /// The name of the root logger (""). + +protected: + typedef std::map<std::string, Logger*> LoggerMap; + + Logger(const std::string& name, Channel* pChannel, int level); + ~Logger(); + + void log(const std::string& text, Message::Priority prio); + void log(const std::string& text, Message::Priority prio, const char* file, int line); + + static std::string format(const std::string& fmt, int argc, std::string argv[]); + static Logger& parent(const std::string& name); + static void add(Logger* pLogger); + static Logger* find(const std::string& name); + +private: + Logger(); + Logger(const Logger&); + Logger& operator = (const Logger&); + + std::string _name; + Channel* _pChannel; + std::atomic_int _level; + + static LoggerMap* _pLoggerMap; + static Mutex _mapMtx; +}; + + +// +// convenience macros +// +#define poco_fatal(logger, msg) \ + if ((logger).fatal()) (logger).fatal(msg, __FILE__, __LINE__); else (void) 0 + +#define poco_fatal_f1(logger, fmt, arg1) \ + if ((logger).fatal()) (logger).fatal(Poco::format((fmt), arg1), __FILE__, __LINE__); else (void) 0 + +#define poco_fatal_f2(logger, fmt, arg1, arg2) \ + if ((logger).fatal()) (logger).fatal(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + +#define poco_fatal_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).fatal()) (logger).fatal(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + +#define poco_fatal_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).fatal()) (logger).fatal(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 + +#define poco_critical(logger, msg) \ + if ((logger).critical()) (logger).critical(msg, __FILE__, __LINE__); else (void) 0 + +#define poco_critical_f1(logger, fmt, arg1) \ + if ((logger).critical()) (logger).critical(Poco::format((fmt), (arg1)), __FILE__, __LINE__); else (void) 0 + +#define poco_critical_f2(logger, fmt, arg1, arg2) \ + if ((logger).critical()) (logger).critical(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + +#define poco_critical_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).critical()) (logger).critical(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + +#define poco_critical_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).critical()) (logger).critical(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 + +#define poco_error(logger, msg) \ + if ((logger).error()) (logger).error(msg, __FILE__, __LINE__); else (void) 0 + +#define poco_error_f1(logger, fmt, arg1) \ + if ((logger).error()) (logger).error(Poco::format((fmt), (arg1)), __FILE__, __LINE__); else (void) 0 + +#define poco_error_f2(logger, fmt, arg1, arg2) \ + if ((logger).error()) (logger).error(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + +#define poco_error_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).error()) (logger).error(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + +#define poco_error_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).error()) (logger).error(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 + +#define poco_warning(logger, msg) \ + if ((logger).warning()) (logger).warning(msg, __FILE__, __LINE__); else (void) 0 + +#define poco_warning_f1(logger, fmt, arg1) \ + if ((logger).warning()) (logger).warning(Poco::format((fmt), (arg1)), __FILE__, __LINE__); else (void) 0 + +#define poco_warning_f2(logger, fmt, arg1, arg2) \ + if ((logger).warning()) (logger).warning(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + +#define poco_warning_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).warning()) (logger).warning(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + +#define poco_warning_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).warning()) (logger).warning(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 + +#define poco_notice(logger, msg) \ + if ((logger).notice()) (logger).notice(msg, __FILE__, __LINE__); else (void) 0 + +#define poco_notice_f1(logger, fmt, arg1) \ + if ((logger).notice()) (logger).notice(Poco::format((fmt), (arg1)), __FILE__, __LINE__); else (void) 0 + +#define poco_notice_f2(logger, fmt, arg1, arg2) \ + if ((logger).notice()) (logger).notice(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + +#define poco_notice_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).notice()) (logger).notice(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + +#define poco_notice_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).notice()) (logger).notice(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 + +#define poco_information(logger, msg) \ + if ((logger).information()) (logger).information(msg, __FILE__, __LINE__); else (void) 0 + +#define poco_information_f1(logger, fmt, arg1) \ + if ((logger).information()) (logger).information(Poco::format((fmt), (arg1)), __FILE__, __LINE__); else (void) 0 + +#define poco_information_f2(logger, fmt, arg1, arg2) \ + if ((logger).information()) (logger).information(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + +#define poco_information_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).information()) (logger).information(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + +#define poco_information_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).information()) (logger).information(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 + +#if defined(_DEBUG) || defined(POCO_LOG_DEBUG) + #define poco_debug(logger, msg) \ + if ((logger).debug()) (logger).debug(msg, __FILE__, __LINE__); else (void) 0 + + #define poco_debug_f1(logger, fmt, arg1) \ + if ((logger).debug()) (logger).debug(Poco::format((fmt), (arg1)), __FILE__, __LINE__); else (void) 0 + + #define poco_debug_f2(logger, fmt, arg1, arg2) \ + if ((logger).debug()) (logger).debug(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + + #define poco_debug_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).debug()) (logger).debug(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + + #define poco_debug_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).debug()) (logger).debug(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 + + #define poco_trace(logger, msg) \ + if ((logger).trace()) (logger).trace(msg, __FILE__, __LINE__); else (void) 0 + + #define poco_trace_f1(logger, fmt, arg1) \ + if ((logger).trace()) (logger).trace(Poco::format((fmt), (arg1)), __FILE__, __LINE__); else (void) 0 + + #define poco_trace_f2(logger, fmt, arg1, arg2) \ + if ((logger).trace()) (logger).trace(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + + #define poco_trace_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).trace()) (logger).trace(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + + #define poco_trace_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).trace()) (logger).trace(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 + + #define poco_test(logger, msg) \ + if ((logger).test()) (logger).test(msg, __FILE__, __LINE__); else (void) 0 + + #define poco_test_f1(logger, fmt, arg1) \ + if ((logger).test()) (logger).test(Poco::format((fmt), (arg1)), __FILE__, __LINE__); else (void) 0 + + #define poco_test_f2(logger, fmt, arg1, arg2) \ + if ((logger).test()) (logger).test(Poco::format((fmt), (arg1), (arg2)), __FILE__, __LINE__); else (void) 0 + + #define poco_test_f3(logger, fmt, arg1, arg2, arg3) \ + if ((logger).test()) (logger).test(Poco::format((fmt), (arg1), (arg2), (arg3)), __FILE__, __LINE__); else (void) 0 + + #define poco_test_f4(logger, fmt, arg1, arg2, arg3, arg4) \ + if ((logger).test()) (logger).test(Poco::format((fmt), (arg1), (arg2), (arg3), (arg4)), __FILE__, __LINE__); else (void) 0 +#else + #define poco_debug(logger, msg) + #define poco_debug_f1(logger, fmt, arg1) + #define poco_debug_f2(logger, fmt, arg1, arg2) + #define poco_debug_f3(logger, fmt, arg1, arg2, arg3) + #define poco_debug_f4(logger, fmt, arg1, arg2, arg3, arg4) + #define poco_trace(logger, msg) + #define poco_trace_f1(logger, fmt, arg1) + #define poco_trace_f2(logger, fmt, arg1, arg2) + #define poco_trace_f3(logger, fmt, arg1, arg2, arg3) + #define poco_trace_f4(logger, fmt, arg1, arg2, arg3, arg4) + #define poco_test(logger, msg) + #define poco_test_f1(logger, fmt, arg1) + #define poco_test_f2(logger, fmt, arg1, arg2) + #define poco_test_f3(logger, fmt, arg1, arg2, arg3) + #define poco_test_f4(logger, fmt, arg1, arg2, arg3, arg4) +#endif + + +// +// inlines +// +inline const std::string& Logger::name() const +{ + return _name; +} + + +inline int Logger::getLevel() const +{ + return _level; +} + + +inline void Logger::log(const std::string& text, Message::Priority prio) +{ + if (_level >= prio && _pChannel) + { + _pChannel->log(Message(_name, text, prio)); + } +} + + +inline void Logger::log(const std::string& text, Message::Priority prio, const char* file, int line) +{ + if (_level >= prio && _pChannel) + { + _pChannel->log(Message(_name, text, prio, file, line)); + } +} + + +inline void Logger::fatal(const std::string& msg) +{ + log(msg, Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_FATAL, file, line); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_FATAL); +} + + +inline void Logger::fatal(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_FATAL); +} + + +inline void Logger::critical(const std::string& msg) +{ + log(msg, Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_CRITICAL, file, line); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_CRITICAL); +} + + +inline void Logger::critical(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_CRITICAL); +} + + +inline void Logger::error(const std::string& msg) +{ + log(msg, Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_ERROR, file, line); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_ERROR); +} + + +inline void Logger::error(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_ERROR); +} + + +inline void Logger::warning(const std::string& msg) +{ + log(msg, Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_WARNING, file, line); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_WARNING); +} + + +inline void Logger::warning(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_WARNING); +} + + +inline void Logger::notice(const std::string& msg) +{ + log(msg, Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_NOTICE, file, line); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_NOTICE); +} + + +inline void Logger::notice(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_NOTICE); +} + + +inline void Logger::information(const std::string& msg) +{ + log(msg, Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_INFORMATION, file, line); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_INFORMATION); +} + + +inline void Logger::information(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_INFORMATION); +} + + +inline void Logger::debug(const std::string& msg) +{ + log(msg, Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_DEBUG, file, line); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_DEBUG); +} + + +inline void Logger::debug(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_DEBUG); +} + + +inline void Logger::trace(const std::string& msg) +{ + log(msg, Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_TRACE, file, line); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_TRACE); +} + + +inline void Logger::trace(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_TRACE); +} + +inline void Logger::test(const std::string& msg) +{ + log(msg, Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& msg, const char* file, int line) +{ + log(msg, Message::PRIO_TEST, file, line); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1) +{ + log(Poco::format(fmt, value1), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2) +{ + log(Poco::format(fmt, value1, value2), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + log(Poco::format(fmt, value1, value2, value3), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + log(Poco::format(fmt, value1, value2, value3, value4), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9), Message::PRIO_TEST); +} + + +inline void Logger::test(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6, const Any& value7, const Any& value8, const Any& value9, const Any& value10) +{ + log(Poco::format(fmt, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10), Message::PRIO_TEST); +} + + +inline bool Logger::is(int level) const +{ + return _level >= level; +} + + +inline bool Logger::fatal() const +{ + return _level >= Message::PRIO_FATAL; +} + + +inline bool Logger::critical() const +{ + return _level >= Message::PRIO_CRITICAL; +} + + +inline bool Logger::error() const +{ + return _level >= Message::PRIO_ERROR; +} + + +inline bool Logger::warning() const +{ + return _level >= Message::PRIO_WARNING; +} + + +inline bool Logger::notice() const +{ + return _level >= Message::PRIO_NOTICE; +} + + +inline bool Logger::information() const +{ + return _level >= Message::PRIO_INFORMATION; +} + + +inline bool Logger::debug() const +{ + return _level >= Message::PRIO_DEBUG; +} + + +inline bool Logger::trace() const +{ + return _level >= Message::PRIO_TRACE; +} + +inline bool Logger::test() const +{ + return _level >= Message::PRIO_TEST; +} + + +} // namespace Poco + + +#endif // Foundation_Logger_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LoggingFactory.h b/contrib/libs/poco/Foundation/include/Poco/LoggingFactory.h new file mode 100644 index 0000000000..c851c3f907 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LoggingFactory.h @@ -0,0 +1,92 @@ +// +// LoggingFactory.h +// +// Library: Foundation +// Package: Logging +// Module: LoggingFactory +// +// Definition of the LoggingFactory class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LoggingFactory_INCLUDED +#define Foundation_LoggingFactory_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DynamicFactory.h" +#include "Poco/Channel.h" +#include "Poco/Formatter.h" + + +namespace Poco { + + +class Foundation_API LoggingFactory + /// An extensible factory for channels and formatters. + /// + /// The following channel classes are pre-registered: + /// - AsyncChannel + /// - ConsoleChannel + /// - EventLogChannel (Windows platforms only) + /// - FileChannel + /// - FormattingChannel + /// - NullChannel + /// - SplitterChannel + /// - SyslogChannel (Unix platforms only) + /// + /// The following formatter classes are pre-registered: + /// - PatternFormatter +{ +public: + typedef AbstractInstantiator<Channel> ChannelInstantiator; + typedef AbstractInstantiator<Formatter> FormatterFactory; + + LoggingFactory(); + /// Creates the LoggingFactory. + /// + /// Automatically registers class factories for the + /// built-in channel and formatter classes. + + ~LoggingFactory(); + /// Destroys the LoggingFactory. + + void registerChannelClass(const std::string& className, ChannelInstantiator* pFactory); + /// Registers a channel class with the LoggingFactory. + + void registerFormatterClass(const std::string& className, FormatterFactory* pFactory); + /// Registers a formatter class with the LoggingFactory. + + Channel* createChannel(const std::string& className) const; + /// Creates a new Channel instance from specified class. + /// + /// Throws a NotFoundException if the specified channel class + /// has not been registered. + + Formatter* createFormatter(const std::string& className) const; + /// Creates a new Formatter instance from specified class. + /// + /// Throws a NotFoundException if the specified formatter class + /// has not been registered. + + static LoggingFactory& defaultFactory(); + /// Returns a reference to the default + /// LoggingFactory. + +private: + void registerBuiltins(); + + DynamicFactory<Channel> _channelFactory; + DynamicFactory<Formatter> _formatterFactory; +}; + + +} // namespace Poco + + +#endif // Foundation_LoggingFactory_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/LoggingRegistry.h b/contrib/libs/poco/Foundation/include/Poco/LoggingRegistry.h new file mode 100644 index 0000000000..82bb2c8588 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/LoggingRegistry.h @@ -0,0 +1,99 @@ +// +// LoggingRegistry.h +// +// Library: Foundation +// Package: Logging +// Module: LoggingRegistry +// +// Definition of the LoggingRegistry class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_LoggingRegistry_INCLUDED +#define Foundation_LoggingRegistry_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AutoPtr.h" +#include "Poco/Channel.h" +#include "Poco/Formatter.h" +#include "Poco/Mutex.h" +#include <map> + + +namespace Poco { + + +class Foundation_API LoggingRegistry + /// A registry for channels and formatters. + /// + /// The LoggingRegistry class is used for configuring + /// the logging framework. +{ +public: + LoggingRegistry(); + /// Creates the LoggingRegistry. + + ~LoggingRegistry(); + /// Destroys the LoggingRegistry. + + Channel* channelForName(const std::string& name) const; + /// Returns the Channel object which has been registered + /// under the given name. + /// + /// Throws a NotFoundException if the name is unknown. + + Formatter* formatterForName(const std::string& name) const; + /// Returns the Formatter object which has been registered + /// under the given name. + /// + /// Throws a NotFoundException if the name is unknown. + + void registerChannel(const std::string& name, Channel* pChannel); + /// Registers a channel under a given name. + /// It is okay to re-register a different channel under an + /// already existing name. + + void registerFormatter(const std::string& name, Formatter* pFormatter); + /// Registers a formatter under a given name. + /// It is okay to re-register a different formatter under an + /// already existing name. + + void unregisterChannel(const std::string& name); + /// Unregisters the given channel. + /// + /// Throws a NotFoundException if the name is unknown. + + void unregisterFormatter(const std::string& name); + /// Unregisters the given formatter. + /// + /// Throws a NotFoundException if the name is unknown. + + void clear(); + /// Unregisters all registered channels and formatters. + + static LoggingRegistry& defaultRegistry(); + /// Returns a reference to the default + /// LoggingRegistry. + +private: + typedef AutoPtr<Channel> ChannelPtr; + typedef AutoPtr<Formatter> FormatterPtr; + typedef std::map<std::string, ChannelPtr> ChannelMap; + typedef std::map<std::string, FormatterPtr> FormatterMap; + + ChannelMap _channelMap; + FormatterMap _formatterMap; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_LoggingRegistry_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/MD4Engine.h b/contrib/libs/poco/Foundation/include/Poco/MD4Engine.h new file mode 100644 index 0000000000..644575e06c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/MD4Engine.h @@ -0,0 +1,95 @@ +// +// MD4Engine.h +// +// Library: Foundation +// Package: Crypt +// Module: MD4Engine +// +// Definition of class MD4Engine. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// +// +// MD4 (RFC 1320) algorithm: +// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All +// rights reserved. +// +// License to copy and use this software is granted provided that it +// is identified as the "RSA Data Security, Inc. MD4 Message-Digest +// Algorithm" in all material mentioning or referencing this software +// or this function. +// +// License is also granted to make and use derivative works provided +// that such works are identified as "derived from the RSA Data +// Security, Inc. MD4 Message-Digest Algorithm" in all material +// mentioning or referencing the derived work. +// +// RSA Data Security, Inc. makes no representations concerning either +// the merchantability of this software or the suitability of this +// software for any particular purpose. It is provided "as is" +// without express or implied warranty of any kind. +// +// These notices must be retained in any copies of any part of this +// documentation and/or software. +// + + +#ifndef Foundation_MD4Engine_INCLUDED +#define Foundation_MD4Engine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" + + +namespace Poco { + + +class Foundation_API MD4Engine: public DigestEngine + /// This class implementes the MD4 message digest algorithm, + /// described in RFC 1320. +{ +public: + enum + { + BLOCK_SIZE = 64, + DIGEST_SIZE = 16 + }; + + MD4Engine(); + ~MD4Engine(); + + std::size_t digestLength() const; + void reset(); + const DigestEngine::Digest& digest(); + +protected: + void updateImpl(const void* data, std::size_t length); + +private: + static void transform(UInt32 state[4], const unsigned char block[64]); + static void encode(unsigned char* output, const UInt32* input, std::size_t len); + static void decode(UInt32* output, const unsigned char* input, std::size_t len); + + struct Context + { + UInt32 state[4]; // state (ABCD) + UInt32 count[2]; // number of bits, modulo 2^64 (lsb first) + unsigned char buffer[64]; // input buffer + }; + + Context _context; + DigestEngine::Digest _digest; + + MD4Engine(const MD4Engine&); + MD4Engine& operator = (const MD4Engine&); +}; + + +} // namespace Poco + + +#endif // Foundation_MD5Engine_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/MD5Engine.h b/contrib/libs/poco/Foundation/include/Poco/MD5Engine.h new file mode 100644 index 0000000000..7835ff6129 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/MD5Engine.h @@ -0,0 +1,95 @@ +// +// MD5Engine.h +// +// Library: Foundation +// Package: Crypt +// Module: MD5Engine +// +// Definition of class MD5Engine. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// +// +// MD5 (RFC 1321) algorithm: +// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All +// rights reserved. +// +// License to copy and use this software is granted provided that it +// is identified as the "RSA Data Security, Inc. MD5 Message-Digest +// Algorithm" in all material mentioning or referencing this software +// or this function. +// +// License is also granted to make and use derivative works provided +// that such works are identified as "derived from the RSA Data +// Security, Inc. MD5 Message-Digest Algorithm" in all material +// mentioning or referencing the derived work. +// +// RSA Data Security, Inc. makes no representations concerning either +// the merchantability of this software or the suitability of this +// software for any particular purpose. It is provided "as is" +// without express or implied warranty of any kind. +// +// These notices must be retained in any copies of any part of this +// documentation and/or software. +// + + +#ifndef Foundation_MD5Engine_INCLUDED +#define Foundation_MD5Engine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" + + +namespace Poco { + + +class Foundation_API MD5Engine: public DigestEngine + /// This class implementes the MD5 message digest algorithm, + /// described in RFC 1321. +{ +public: + enum + { + BLOCK_SIZE = 64, + DIGEST_SIZE = 16 + }; + + MD5Engine(); + ~MD5Engine(); + + std::size_t digestLength() const; + void reset(); + const DigestEngine::Digest& digest(); + +protected: + void updateImpl(const void* data, std::size_t length); + +private: + static void transform(UInt32 state[4], const unsigned char block[64]); + static void encode(unsigned char* output, const UInt32* input, std::size_t len); + static void decode(UInt32* output, const unsigned char* input, std::size_t len); + + struct Context + { + UInt32 state[4]; // state (ABCD) + UInt32 count[2]; // number of bits, modulo 2^64 (lsb first) + unsigned char buffer[64]; // input buffer + }; + + Context _context; + DigestEngine::Digest _digest; + + MD5Engine(const MD5Engine&); + MD5Engine& operator = (const MD5Engine&); +}; + + +} // namespace Poco + + +#endif // Foundation_MD5Engine_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Manifest.h b/contrib/libs/poco/Foundation/include/Poco/Manifest.h new file mode 100644 index 0000000000..d59bc04c36 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Manifest.h @@ -0,0 +1,180 @@ +// +// Manifest.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Definition of the Manifest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Manifest_INCLUDED +#define Foundation_Manifest_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/MetaObject.h" +#include <map> +#include <typeinfo> + + +namespace Poco { + + +class Foundation_API ManifestBase + /// ManifestBase is a common base class for + /// all instantiations of Manifest. +{ +public: + ManifestBase(); + virtual ~ManifestBase(); + + virtual const char* className() const = 0; + /// Returns the type name of the manifest's class. +}; + + +template <class B> +class Manifest: public ManifestBase + /// A Manifest maintains a list of all classes + /// contained in a dynamically loadable class + /// library. + /// Internally, the information is held + /// in a map. An iterator is provided to + /// iterate over all the classes in a Manifest. +{ +public: + typedef AbstractMetaObject<B> Meta; + typedef std::map<std::string, const Meta*> MetaMap; + + class Iterator + /// The Manifest's very own iterator class. + { + public: + Iterator(const typename MetaMap::const_iterator& it) + { + _it = it; + } + Iterator(const Iterator& it) + { + _it = it._it; + } + ~Iterator() + { + } + Iterator& operator = (const Iterator& it) + { + _it = it._it; + return *this; + } + inline bool operator == (const Iterator& it) const + { + return _it == it._it; + } + inline bool operator != (const Iterator& it) const + { + return _it != it._it; + } + Iterator& operator ++ () // prefix + { + ++_it; + return *this; + } + Iterator operator ++ (int) // postfix + { + Iterator result(_it); + ++_it; + return result; + } + inline const Meta* operator * () const + { + return _it->second; + } + inline const Meta* operator -> () const + { + return _it->second; + } + + private: + typename MetaMap::const_iterator _it; + }; + + Manifest() + /// Creates an empty Manifest. + { + } + + virtual ~Manifest() + /// Destroys the Manifest. + { + clear(); + } + + Iterator find(const std::string& rClassName) const + /// Returns an iterator pointing to the MetaObject + /// for the given class. If the MetaObject cannot + /// be found, the iterator points to end(). + { + return Iterator(_metaMap.find(rClassName)); + } + + Iterator begin() const + { + return Iterator(_metaMap.begin()); + } + + Iterator end() const + { + return Iterator(_metaMap.end()); + } + + bool insert(const Meta* pMeta) + /// Inserts a MetaObject. Returns true if insertion + /// was successful, false if a class with the same + /// name already exists. + { + return _metaMap.insert(typename MetaMap::value_type(pMeta->name(), pMeta)).second; + } + + void clear() + /// Removes all MetaObjects from the manifest. + { + for (typename MetaMap::iterator it = _metaMap.begin(); it != _metaMap.end(); ++it) + { + delete it->second; + } + _metaMap.clear(); + } + + int size() const + /// Returns the number of MetaObjects in the Manifest. + { + return int(_metaMap.size()); + } + + bool empty() const + /// Returns true iff the Manifest does not contain any MetaObjects. + { + return _metaMap.empty(); + } + + const char* className() const + { + return typeid(*this).name(); + } + +private: + MetaMap _metaMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Manifest_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/MemoryPool.h b/contrib/libs/poco/Foundation/include/Poco/MemoryPool.h new file mode 100644 index 0000000000..55f238d991 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/MemoryPool.h @@ -0,0 +1,115 @@ +// +// MemoryPool.h +// +// Library: Foundation +// Package: Core +// Module: MemoryPool +// +// Definition of the MemoryPool class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_MemoryPool_INCLUDED +#define Foundation_MemoryPool_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include <vector> +#include <cstddef> + + +namespace Poco { + + +class Foundation_API MemoryPool + /// A simple pool for fixed-size memory blocks. + /// + /// The main purpose of this class is to speed-up + /// memory allocations, as well as to reduce memory + /// fragmentation in situations where the same blocks + /// are allocated all over again, such as in server + /// applications. + /// + /// All allocated blocks are retained for future use. + /// A limit on the number of blocks can be specified. + /// Blocks can be preallocated. +{ +public: + MemoryPool(std::size_t blockSize, int preAlloc = 0, int maxAlloc = 0); + /// Creates a MemoryPool for blocks with the given blockSize. + /// The number of blocks given in preAlloc are preallocated. + + ~MemoryPool(); + + void* get(); + /// Returns a memory block. If there are no more blocks + /// in the pool, a new block will be allocated. + /// + /// If maxAlloc blocks are already allocated, an + /// OutOfMemoryException is thrown. + + void release(void* ptr); + /// Releases a memory block and returns it to the pool. + + std::size_t blockSize() const; + /// Returns the block size. + + int allocated() const; + /// Returns the number of allocated blocks. + + int available() const; + /// Returns the number of available blocks in the pool. + +private: + MemoryPool(); + MemoryPool(const MemoryPool&); + MemoryPool& operator = (const MemoryPool&); + + void clear(); + + enum + { + BLOCK_RESERVE = 128 + }; + + typedef std::vector<char*> BlockVec; + + std::size_t _blockSize; + int _maxAlloc; + int _allocated; + BlockVec _blocks; + FastMutex _mutex; +}; + + +// +// inlines +// +inline std::size_t MemoryPool::blockSize() const +{ + return _blockSize; +} + + +inline int MemoryPool::allocated() const +{ + return _allocated; +} + + +inline int MemoryPool::available() const +{ + return (int) _blocks.size(); +} + + +} // namespace Poco + + +#endif // Foundation_MemoryPool_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/MemoryStream.h b/contrib/libs/poco/Foundation/include/Poco/MemoryStream.h new file mode 100644 index 0000000000..819f160942 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/MemoryStream.h @@ -0,0 +1,246 @@ +// +// MemoryStream.h +// +// Library: Foundation +// Package: Streams +// Module: MemoryStream +// +// Definition of MemoryStreamBuf, MemoryInputStream, MemoryOutputStream +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_MemoryStream_INCLUDED +#define Foundation_MemoryStream_INCLUDED + + +#include "Poco/Bugcheck.h" +#include "Poco/Foundation.h" +#include "Poco/StreamUtil.h" +#include <streambuf> +#include <iosfwd> +#include <ios> +#include <istream> +#include <ostream> + + +namespace Poco { + + +template <typename ch, typename tr> +class BasicMemoryStreamBuf: public std::basic_streambuf<ch, tr> + /// BasicMemoryStreamBuf is a simple implementation of a + /// stream buffer for reading and writing from a memory area. + /// + /// This streambuf only supports unidirectional streams. + /// In other words, the BasicMemoryStreamBuf can be + /// used for the implementation of an istream or an + /// ostream, but not for an iostream. +{ +protected: + typedef std::basic_streambuf<ch, tr> Base; + typedef std::basic_ios<ch, tr> IOS; + typedef ch char_type; + typedef tr char_traits; + typedef typename Base::int_type int_type; + typedef typename Base::pos_type pos_type; + typedef typename Base::off_type off_type; + +public: + BasicMemoryStreamBuf(char_type* pBuffer, std::streamsize bufferSize): + _pBuffer(pBuffer), + _bufferSize(bufferSize) + { + this->setg(_pBuffer, _pBuffer, _pBuffer + _bufferSize); + this->setp(_pBuffer, _pBuffer + _bufferSize); + } + + ~BasicMemoryStreamBuf() + { + } + + virtual int_type overflow(int_type /*c*/) + { + return char_traits::eof(); + } + + virtual int_type underflow() + { + return char_traits::eof(); + } + + virtual pos_type seekoff(off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out) + { + const pos_type fail = off_type(-1); + off_type newoff = off_type(-1); + + if ((which & std::ios_base::in) != 0) + { + if (this->gptr() == 0) + return fail; + + if (way == std::ios_base::beg) + { + newoff = 0; + } + else if (way == std::ios_base::cur) + { + // cur is not valid if both in and out are specified (Condition 3) + if ((which & std::ios_base::out) != 0) + return fail; + newoff = this->gptr() - this->eback(); + } + else if (way == std::ios_base::end) + { + newoff = this->egptr() - this->eback(); + } + else + { + poco_bugcheck(); + } + + if ((newoff + off) < 0 || (this->egptr() - this->eback()) < (newoff + off)) + return fail; + this->setg(this->eback(), this->eback() + newoff + off, this->egptr()); + } + + if ((which & std::ios_base::out) != 0) + { + if (this->pptr() == 0) + return fail; + + if (way == std::ios_base::beg) + { + newoff = 0; + } + else if (way == std::ios_base::cur) + { + // cur is not valid if both in and out are specified (Condition 3) + if ((which & std::ios_base::in) != 0) + return fail; + newoff = this->pptr() - this->pbase(); + } + else if (way == std::ios_base::end) + { + newoff = this->epptr() - this->pbase(); + } + else + { + poco_bugcheck(); + } + + if (newoff + off < 0 || (this->epptr() - this->pbase()) < newoff + off) + return fail; + this->pbump((int)(newoff + off - (this->pptr() - this->pbase()))); + } + + return newoff; + } + + virtual int sync() + { + return 0; + } + + std::streamsize charsWritten() const + { + return static_cast<std::streamsize>(this->pptr() - this->pbase()); + } + + void reset() + /// Resets the buffer so that current read and write positions + /// will be set to the beginning of the buffer. + { + this->setg(_pBuffer, _pBuffer, _pBuffer + _bufferSize); + this->setp(_pBuffer, _pBuffer + _bufferSize); + } + +private: + char_type* _pBuffer; + std::streamsize _bufferSize; + + BasicMemoryStreamBuf(); + BasicMemoryStreamBuf(const BasicMemoryStreamBuf&); + BasicMemoryStreamBuf& operator = (const BasicMemoryStreamBuf&); +}; + + +// +// We provide an instantiation for char +// +typedef BasicMemoryStreamBuf<char, std::char_traits<char> > MemoryStreamBuf; + + +class Foundation_API MemoryIOS: public virtual std::ios + /// The base class for MemoryInputStream and MemoryOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + MemoryIOS(char* pBuffer, std::streamsize bufferSize); + /// Creates the basic stream. + + ~MemoryIOS(); + /// Destroys the stream. + + MemoryStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + MemoryStreamBuf _buf; +}; + + +class Foundation_API MemoryInputStream: public MemoryIOS, public std::istream + /// An input stream for reading from a memory area. +{ +public: + MemoryInputStream(const char* pBuffer, std::streamsize bufferSize); + /// Creates a MemoryInputStream for the given memory area, + /// ready for reading. + + ~MemoryInputStream(); + /// Destroys the MemoryInputStream. +}; + + +class Foundation_API MemoryOutputStream: public MemoryIOS, public std::ostream + /// An input stream for reading from a memory area. +{ +public: + MemoryOutputStream(char* pBuffer, std::streamsize bufferSize); + /// Creates a MemoryOutputStream for the given memory area, + /// ready for writing. + + ~MemoryOutputStream(); + /// Destroys the MemoryInputStream. + + std::streamsize charsWritten() const; + /// Returns the number of chars written to the buffer. +}; + + +// +// inlines +// +inline MemoryStreamBuf* MemoryIOS::rdbuf() +{ + return &_buf; +} + + +inline std::streamsize MemoryOutputStream::charsWritten() const +{ + return _buf.charsWritten(); +} + + +} // namespace Poco + + +#endif // Foundation_MemoryStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Message.h b/contrib/libs/poco/Foundation/include/Poco/Message.h new file mode 100644 index 0000000000..8b0c49afa2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Message.h @@ -0,0 +1,272 @@ +// +// Message.h +// +// Library: Foundation +// Package: Logging +// Module: Message +// +// Definition of the Message class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Message_INCLUDED +#define Foundation_Message_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include <map> + + +namespace Poco { + + +class Foundation_API Message + /// This class represents a log message that is sent through a + /// chain of log channels. + /// + /// A Message contains a priority denoting the severity of the + /// message, a source describing its origin, a text describing + /// its meaning, the time of its creation, and an identifier of + /// the process and thread that created the message. + /// + /// Optionally a Message can also contain the source file path + /// and line number of the statement generating the message. + /// + /// A Message can also contain any number of named parameters + /// that contain additional information about the event that + /// caused the message. +{ +public: + enum Priority + { + PRIO_FATAL = 1, /// A fatal error. The application will most likely terminate. This is the highest priority. + PRIO_CRITICAL, /// A critical error. The application might not be able to continue running successfully. + PRIO_ERROR, /// An error. An operation did not complete successfully, but the application as a whole is not affected. + PRIO_WARNING, /// A warning. An operation completed with an unexpected result. + PRIO_NOTICE, /// A notice, which is an information with just a higher priority. + PRIO_INFORMATION, /// An informational message, usually denoting the successful completion of an operation. + PRIO_DEBUG, /// A debugging message. + PRIO_TRACE, /// A tracing message. This is the lowest priority useful for production. + PRIO_TEST /// A message for test environment. + }; + + Message(); + /// Creates an empty Message. + /// The thread and process ids are set. + + Message(const std::string& source, const std::string& text, Priority prio); + /// Creates a Message with the given source, text and priority. + /// The thread and process ids are set. + + Message(const std::string& source, const std::string& text, Priority prio, const char* file, int line); + /// Creates a Message with the given source, text, priority, + /// source file path and line. + /// + /// The source file path must be a + /// static string with a lifetime that's at least the lifetime + /// of the message object (the string is not copied internally). + /// Usually, this will be the path string obtained from the + /// __FILE__ macro. + /// + /// The thread and process ids are set. + + Message(const Message& msg); + /// Creates a Message by copying another one. + + Message(const Message& msg, const std::string& text); + /// Creates a Message by copying all but the text from another message. + + ~Message(); + /// Destroys the Message. + + Message& operator = (const Message& msg); + /// Assignment operator. + + void swap(Message& msg); + /// Swaps the message with another one. + + void setSource(const std::string& src); + /// Sets the source of the message. + + const std::string& getSource() const; + /// Returns the source of the message. + + void setText(const std::string& text); + /// Sets the text of the message. + + const std::string& getText() const; + /// Returns the text of the message. + + void setPriority(Priority prio); + /// Sets the priority of the message. + + Priority getPriority() const; + /// Returns the priority of the message. + + void setTime(const Timestamp& time); + /// Sets the time of the message. + + const Timestamp& getTime() const; + /// Returns the time of the message. + + void setThread(const std::string& thread); + /// Sets the thread identifier for the message. + + const std::string& getThread() const; + /// Returns the thread identifier for the message. + + void setTid(long pid); + /// Sets the numeric thread identifier for the message. + + long getTid() const; + /// Returns the numeric thread identifier for the message. + + void setPid(long pid); + /// Sets the process identifier for the message. + + long getPid() const; + /// Returns the process identifier for the message. + + void setSourceFile(const char* file); + /// Sets the source file path of the statement + /// generating the log message. + /// + /// File must be a static string, such as the value of + /// the __FILE__ macro. The string is not copied + /// internally for performance reasons. + + const char* getSourceFile() const; + /// Returns the source file path of the code creating + /// the message. May be 0 if not set. + + void setSourceLine(int line); + /// Sets the source file line of the statement + /// generating the log message. + /// + /// This is usually the result of the __LINE__ + /// macro. + + int getSourceLine() const; + /// Returns the source file line of the statement + /// generating the log message. May be 0 + /// if not set. + + bool has(const std::string& param) const; + /// Returns true if a parameter with the given name exists. + + const std::string& get(const std::string& param) const; + /// Returns a const reference to the value of the parameter + /// with the given name. Throws a NotFoundException if the + /// parameter does not exist. + + const std::string& get(const std::string& param, const std::string& defaultValue) const; + /// Returns a const reference to the value of the parameter + /// with the given name. If the parameter with the given name + /// does not exist, then defaultValue is returned. + + void set(const std::string& param, const std::string& value); + /// Sets the value for a parameter. If the parameter does + /// not exist, then it is created. + + const std::string& operator [] (const std::string& param) const; + /// Returns a const reference to the value of the parameter + /// with the given name. Throws a NotFoundException if the + /// parameter does not exist. + + std::string& operator [] (const std::string& param); + /// Returns a reference to the value of the parameter with the + /// given name. This can be used to set the parameter's value. + /// If the parameter does not exist, it is created with an + /// empty string value. + +protected: + void init(); + typedef std::map<std::string, std::string> StringMap; + +private: + std::string _source; + std::string _text; + Priority _prio; + Timestamp _time; + long _tid; + std::string _thread; + long _pid; + const char* _file; + int _line; + StringMap* _pMap; +}; + + +// +// inlines +// +inline const std::string& Message::getSource() const +{ + return _source; +} + + +inline const std::string& Message::getText() const +{ + return _text; +} + + +inline Message::Priority Message::getPriority() const +{ + return _prio; +} + + +inline const Timestamp& Message::getTime() const +{ + return _time; +} + + +inline const std::string& Message::getThread() const +{ + return _thread; +} + + +inline long Message::getTid() const +{ + return _tid; +} + + +inline long Message::getPid() const +{ + return _pid; +} + + +inline const char* Message::getSourceFile() const +{ + return _file; +} + + +inline int Message::getSourceLine() const +{ + return _line; +} + + +inline void swap(Message& m1, Message& m2) +{ + m1.swap(m2); +} + + +} // namespace Poco + + +#endif // Foundation_Message_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/MetaObject.h b/contrib/libs/poco/Foundation/include/Poco/MetaObject.h new file mode 100644 index 0000000000..1b75c28009 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/MetaObject.h @@ -0,0 +1,201 @@ +// +// MetaObject.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Definition of the MetaObject class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_MetaObject_INCLUDED +#define Foundation_MetaObject_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/SingletonHolder.h" +#include <set> + + +namespace Poco { + + +template <class B> +class AbstractMetaObject + /// A MetaObject stores some information + /// about a C++ class. The MetaObject class + /// is used by the Manifest class. + /// AbstractMetaObject is a common base class + /// for all MetaObject in a rooted class hierarchy. + /// A MetaObject can also be used as an object + /// factory for its class. +{ +public: + AbstractMetaObject(const char* pName): _name(pName) + { + } + + virtual ~AbstractMetaObject() + { + for (typename ObjectSet::iterator it = _deleteSet.begin(); it != _deleteSet.end(); ++it) + { + delete *it; + } + } + + const char* name() const + { + return _name; + } + + virtual B* create() const = 0; + /// Create a new instance of a class. + /// Cannot be used for singletons. + + virtual B& instance() const = 0; + /// Returns a reference to the only instance + /// of the class. Used for singletons only. + + virtual bool canCreate() const = 0; + /// Returns true iff the create method can be used + /// to create instances of the class. + /// Returns false if the class is a singleton. + + virtual void destroy(B* pObject) const + /// If pObject was owned by meta object, the + /// ownership of the deleted object is removed + /// and the object is deleted. + { + typename ObjectSet::iterator it = _deleteSet.find(pObject); + + if (it != _deleteSet.end()) + { + _deleteSet.erase(pObject); + delete pObject; + } + } + + B* autoDelete(B* pObject) const + /// Give ownership of pObject to the meta object. + /// The meta object will delete all objects it owns + /// when it is destroyed. + /// + /// Returns pObject. + { + if (this->canCreate()) // guard against singleton + { + poco_check_ptr (pObject); + _deleteSet.insert(pObject); + } + else throw InvalidAccessException("Cannot take ownership of", this->name()); + + return pObject; + } + + virtual bool isAutoDelete(B* pObject) const + /// Returns true if the object is owned + /// by meta object. + /// + /// Overloaded in MetaSingleton - returns true + /// if the class is a singleton. + { + return _deleteSet.find(pObject) != _deleteSet.end(); + } + +private: + AbstractMetaObject(); + AbstractMetaObject(const AbstractMetaObject&); + AbstractMetaObject& operator = (const AbstractMetaObject&); + + typedef std::set<B*> ObjectSet; + + const char* _name; + mutable ObjectSet _deleteSet; +}; + + +template <class C, class B> +class MetaObject: public AbstractMetaObject<B> + /// A MetaObject stores some information + /// about a C++ class. The MetaObject class + /// is used by the Manifest class. + /// A MetaObject can also be used as an object + /// factory for its class. +{ +public: + MetaObject(const char* name): AbstractMetaObject<B>(name) + { + } + + ~MetaObject() + { + } + + B* create() const + { + return new C; + } + + B& instance() const + { + throw InvalidAccessException("Not a singleton. Use create() to create instances of", this->name()); + } + + bool canCreate() const + { + return true; + } +}; + + +template <class C, class B> +class MetaSingleton: public AbstractMetaObject<B> + /// A SingletonMetaObject disables the create() method + /// and instead offers an instance() method to access + /// the single instance of its class. +{ +public: + MetaSingleton(const char* name): AbstractMetaObject<B>(name) + { + } + + ~MetaSingleton() + { + } + + B* create() const + { + throw InvalidAccessException("Cannot create instances of a singleton class. Use instance() to obtain a", this->name()); + } + + bool canCreate() const + { + return false; + } + + B& instance() const + { + return *_object.get(); + } + + bool isAutoDelete(B* /*pObject*/) const + { + return true; + } + +private: + mutable SingletonHolder<C> _object; +}; + + +} // namespace Poco + + +#endif // Foundation_MetaObject_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/MetaProgramming.h b/contrib/libs/poco/Foundation/include/Poco/MetaProgramming.h new file mode 100644 index 0000000000..ba68fe054c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/MetaProgramming.h @@ -0,0 +1,144 @@ +// +// MetaProgramming.h +// +// Library: Foundation +// Package: Core +// Module: MetaProgramming +// +// Common definitions useful for Meta Template Programming +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_MetaProgramming_INCLUDED +#define Foundation_MetaProgramming_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template <typename T> +struct IsReference + /// Use this struct to determine if a template type is a reference. +{ + enum + { + VALUE = 0 + }; +}; + + +template <typename T> +struct IsReference<T&> +{ + enum + { + VALUE = 1 + }; +}; + + +template <typename T> +struct IsReference<const T&> +{ + enum + { + VALUE = 1 + }; +}; + + +template <typename T> +struct IsConst + /// Use this struct to determine if a template type is a const type. +{ + enum + { + VALUE = 0 + }; +}; + + +template <typename T> +struct IsConst<const T&> +{ + enum + { + VALUE = 1 + }; +}; + + +template <typename T> +struct IsConst<const T> +{ + enum + { + VALUE = 1 + }; +}; + + +template <typename T, int i> +struct IsConst<const T[i]> + /// Specialization for const char arrays +{ + enum + { + VALUE = 1 + }; +}; + + +template <typename T> +struct TypeWrapper + /// Use the type wrapper if you want to decouple constness and references from template types. +{ + typedef T TYPE; + typedef const T CONSTTYPE; + typedef T& REFTYPE; + typedef const T& CONSTREFTYPE; +}; + + +template <typename T> +struct TypeWrapper<const T> +{ + typedef T TYPE; + typedef const T CONSTTYPE; + typedef T& REFTYPE; + typedef const T& CONSTREFTYPE; +}; + + +template <typename T> +struct TypeWrapper<const T&> +{ + typedef T TYPE; + typedef const T CONSTTYPE; + typedef T& REFTYPE; + typedef const T& CONSTREFTYPE; +}; + + +template <typename T> +struct TypeWrapper<T&> +{ + typedef T TYPE; + typedef const T CONSTTYPE; + typedef T& REFTYPE; + typedef const T& CONSTREFTYPE; +}; + + +} // namespace Poco + + +#endif // Foundation_MetaProgramming_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Mutex.h b/contrib/libs/poco/Foundation/include/Poco/Mutex.h new file mode 100644 index 0000000000..64d0efc06d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Mutex.h @@ -0,0 +1,270 @@ +// +// Mutex.h +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the Mutex and FastMutex classes. +// +// Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Mutex_INCLUDED +#define Foundation_Mutex_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/ScopedLock.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#if defined(_WIN32_WCE) +#include "Poco/Mutex_WINCE.h" +#else +#include "Poco/Mutex_WIN32.h" +#endif +#elif defined(POCO_VXWORKS) +#include "Poco/Mutex_VX.h" +#else +#include "Poco/Mutex_POSIX.h" +#endif + + +namespace Poco { + + +class Foundation_API Mutex: private MutexImpl + /// A Mutex (mutual exclusion) is a synchronization + /// mechanism used to control access to a shared resource + /// in a concurrent (multithreaded) scenario. + /// Mutexes are recursive, that is, the same mutex can be + /// locked multiple times by the same thread (but, of course, + /// not by other threads). + /// Using the ScopedLock class is the preferred way to automatically + /// lock and unlock a mutex. +{ +public: + typedef Poco::ScopedLock<Mutex> ScopedLock; + + Mutex(); + /// creates the Mutex. + + ~Mutex(); + /// destroys the Mutex. + + void lock(); + /// Locks the mutex. Blocks if the mutex + /// is held by another thread. + + void lock(long milliseconds); + /// Locks the mutex. Blocks up to the given number of milliseconds + /// if the mutex is held by another thread. Throws a TimeoutException + /// if the mutex can not be locked within the given timeout. + /// + /// Performance Note: On most platforms (including Windows), this member function is + /// implemented using a loop calling (the equivalent of) tryLock() and Thread::sleep(). + /// On POSIX platforms that support pthread_mutex_timedlock(), this is used. + + bool tryLock(); + /// Tries to lock the mutex. Returns false immediately + /// if the mutex is already held by another thread. + /// Returns true if the mutex was successfully locked. + + bool tryLock(long milliseconds); + /// Locks the mutex. Blocks up to the given number of milliseconds + /// if the mutex is held by another thread. + /// Returns true if the mutex was successfully locked. + /// + /// Performance Note: On most platforms (including Windows), this member function is + /// implemented using a loop calling (the equivalent of) tryLock() and Thread::sleep(). + /// On POSIX platforms that support pthread_mutex_timedlock(), this is used. + + void unlock(); + /// Unlocks the mutex so that it can be acquired by + /// other threads. + +private: + Mutex(const Mutex&); + Mutex& operator = (const Mutex&); +}; + + +class Foundation_API FastMutex: private FastMutexImpl + /// A FastMutex (mutual exclusion) is similar to a Mutex. + /// Unlike a Mutex, however, a FastMutex is not recursive, + /// which means that a deadlock will occur if the same + /// thread tries to lock a mutex it has already locked again. + /// Locking a FastMutex is faster than locking a recursive Mutex. + /// Using the ScopedLock class is the preferred way to automatically + /// lock and unlock a mutex. +{ +public: + typedef Poco::ScopedLock<FastMutex> ScopedLock; + + FastMutex(); + /// creates the Mutex. + + ~FastMutex(); + /// destroys the Mutex. + + void lock(); + /// Locks the mutex. Blocks if the mutex + /// is held by another thread. + + void lock(long milliseconds); + /// Locks the mutex. Blocks up to the given number of milliseconds + /// if the mutex is held by another thread. Throws a TimeoutException + /// if the mutex can not be locked within the given timeout. + /// + /// Performance Note: On most platforms (including Windows), this member function is + /// implemented using a loop calling (the equivalent of) tryLock() and Thread::sleep(). + /// On POSIX platforms that support pthread_mutex_timedlock(), this is used. + + bool tryLock(); + /// Tries to lock the mutex. Returns false immediately + /// if the mutex is already held by another thread. + /// Returns true if the mutex was successfully locked. + + bool tryLock(long milliseconds); + /// Locks the mutex. Blocks up to the given number of milliseconds + /// if the mutex is held by another thread. + /// Returns true if the mutex was successfully locked. + /// + /// Performance Note: On most platforms (including Windows), this member function is + /// implemented using a loop calling (the equivalent of) tryLock() and Thread::sleep(). + /// On POSIX platforms that support pthread_mutex_timedlock(), this is used. + + void unlock(); + /// Unlocks the mutex so that it can be acquired by + /// other threads. + +private: + FastMutex(const FastMutex&); + FastMutex& operator = (const FastMutex&); +}; + + +class Foundation_API NullMutex + /// A NullMutex is an empty mutex implementation + /// which performs no locking at all. Useful in policy driven design + /// where the type of mutex used can be now a template parameter allowing the user to switch + /// between thread-safe and not thread-safe depending on his need + /// Works with the ScopedLock class +{ +public: + typedef Poco::ScopedLock<NullMutex> ScopedLock; + + NullMutex() + /// Creates the NullMutex. + { + } + + ~NullMutex() + /// Destroys the NullMutex. + { + } + + void lock() + /// Does nothing. + { + } + + void lock(long) + /// Does nothing. + { + } + + bool tryLock() + /// Does nothing and always returns true. + { + return true; + } + + bool tryLock(long) + /// Does nothing and always returns true. + { + return true; + } + + void unlock() + /// Does nothing. + { + } +}; + + +// +// inlines +// +inline void Mutex::lock() +{ + lockImpl(); +} + + +inline void Mutex::lock(long milliseconds) +{ + if (!tryLockImpl(milliseconds)) + throw TimeoutException(); +} + + +inline bool Mutex::tryLock() +{ + return tryLockImpl(); +} + + +inline bool Mutex::tryLock(long milliseconds) +{ + return tryLockImpl(milliseconds); +} + + +inline void Mutex::unlock() +{ + unlockImpl(); +} + + +inline void FastMutex::lock() +{ + lockImpl(); +} + + +inline void FastMutex::lock(long milliseconds) +{ + if (!tryLockImpl(milliseconds)) + throw TimeoutException(); +} + + +inline bool FastMutex::tryLock() +{ + return tryLockImpl(); +} + + +inline bool FastMutex::tryLock(long milliseconds) +{ + return tryLockImpl(milliseconds); +} + + +inline void FastMutex::unlock() +{ + unlockImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_Mutex_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Mutex_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/Mutex_POSIX.h new file mode 100644 index 0000000000..12f61dd689 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Mutex_POSIX.h @@ -0,0 +1,86 @@ +// +// Mutex_POSIX.h +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the MutexImpl and FastMutexImpl classes for POSIX Threads. +// +// Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Mutex_POSIX_INCLUDED +#define Foundation_Mutex_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <pthread.h> +#include <errno.h> + + +namespace Poco { + + +class Foundation_API MutexImpl +{ +protected: + MutexImpl(); + MutexImpl(bool fast); + ~MutexImpl(); + void lockImpl(); + bool tryLockImpl(); + bool tryLockImpl(long milliseconds); + void unlockImpl(); + +private: + pthread_mutex_t _mutex; +}; + + +class Foundation_API FastMutexImpl: public MutexImpl +{ +protected: + FastMutexImpl(); + ~FastMutexImpl(); +}; + + +// +// inlines +// +inline void MutexImpl::lockImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot lock mutex"); +} + + +inline bool MutexImpl::tryLockImpl() +{ + int rc = pthread_mutex_trylock(&_mutex); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock mutex"); +} + + +inline void MutexImpl::unlockImpl() +{ + if (pthread_mutex_unlock(&_mutex)) + throw SystemException("cannot unlock mutex"); +} + + +} // namespace Poco + + +#endif // Foundation_Mutex_POSIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Mutex_VX.h b/contrib/libs/poco/Foundation/include/Poco/Mutex_VX.h new file mode 100644 index 0000000000..f0f43eac3a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Mutex_VX.h @@ -0,0 +1,80 @@ +// +// Mutex_VX.h +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the MutexImpl and FastMutexImpl classes for VxWorks. +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Mutex_VX_INCLUDED +#define Foundation_Mutex_VX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <semLib.h> +#include <errno.h> + + +namespace Poco { + + +class Foundation_API MutexImpl +{ +protected: + MutexImpl(); + MutexImpl(bool fast); + ~MutexImpl(); + void lockImpl(); + bool tryLockImpl(); + bool tryLockImpl(long milliseconds); + void unlockImpl(); + +private: + SEM_ID _sem; +}; + + +class Foundation_API FastMutexImpl: public MutexImpl +{ +protected: + FastMutexImpl(); + ~FastMutexImpl(); +}; + + +// +// inlines +// +inline void MutexImpl::lockImpl() +{ + if (semTake(_sem, WAIT_FOREVER) != OK) + throw SystemException("cannot lock mutex"); +} + + +inline bool MutexImpl::tryLockImpl() +{ + return semTake(_sem, NO_WAIT) == OK; +} + + +inline void MutexImpl::unlockImpl() +{ + if (semGive(_sem) != OK) + throw SystemException("cannot unlock mutex"); +} + + +} // namespace Poco + + +#endif // Foundation_Mutex_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Mutex_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/Mutex_WIN32.h new file mode 100644 index 0000000000..8e18c527ea --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Mutex_WIN32.h @@ -0,0 +1,85 @@ +// +// Mutex_WIN32.h +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the MutexImpl and FastMutexImpl classes for WIN32. +// +// Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Mutex_WIN32_INCLUDED +#define Foundation_Mutex_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API MutexImpl +{ +protected: + MutexImpl(); + ~MutexImpl(); + void lockImpl(); + bool tryLockImpl(); + bool tryLockImpl(long milliseconds); + void unlockImpl(); + +private: + CRITICAL_SECTION _cs; +}; + + +typedef MutexImpl FastMutexImpl; + + +// +// inlines +// +inline void MutexImpl::lockImpl() +{ + try + { + EnterCriticalSection(&_cs); + } + catch (...) + { + throw SystemException("cannot lock mutex"); + } +} + + +inline bool MutexImpl::tryLockImpl() +{ + try + { + return TryEnterCriticalSection(&_cs) != 0; + } + catch (...) + { + } + throw SystemException("cannot lock mutex"); +} + + +inline void MutexImpl::unlockImpl() +{ + LeaveCriticalSection(&_cs); +} + + +} // namespace Poco + + +#endif // Foundation_Mutex_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Mutex_WINCE.h b/contrib/libs/poco/Foundation/include/Poco/Mutex_WINCE.h new file mode 100644 index 0000000000..27200680f1 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Mutex_WINCE.h @@ -0,0 +1,50 @@ +// +// Mutex_WIN32.h +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the MutexImpl and FastMutexImpl classes for WIN32. +// +// Copyright (c) 2004-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Mutex_WINCE_INCLUDED +#define Foundation_Mutex_WINCE_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API MutexImpl +{ +protected: + MutexImpl(); + ~MutexImpl(); + void lockImpl(); + bool tryLockImpl(); + bool tryLockImpl(long milliseconds); + void unlockImpl(); + +private: + HANDLE _mutex; +}; + + +typedef MutexImpl FastMutexImpl; + + +} // namespace Poco + + +#endif // Foundation_Mutex_WINCE_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NObserver.h b/contrib/libs/poco/Foundation/include/Poco/NObserver.h new file mode 100644 index 0000000000..8b5106c8b0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NObserver.h @@ -0,0 +1,126 @@ +// +// NObserver.h +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Definition of the NObserver class template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NObserver_INCLUDED +#define Foundation_NObserver_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractObserver.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class C, class N> +class NObserver: public AbstractObserver + /// This template class implements an adapter that sits between + /// a NotificationCenter and an object receiving notifications + /// from it. It is quite similar in concept to the + /// RunnableAdapter, but provides some NotificationCenter + /// specific additional methods. + /// See the NotificationCenter class for information on how + /// to use this template class. + /// + /// This class template is quite similar to the Observer class + /// template. The only difference is that the NObserver + /// expects the callback function to accept a const AutoPtr& + /// instead of a plain pointer as argument, thus simplifying memory + /// management. +{ +public: + typedef AutoPtr<N> NotificationPtr; + typedef void (C::*Callback)(const NotificationPtr&); + + NObserver(C& object, Callback method): + _pObject(&object), + _method(method) + { + } + + NObserver(const NObserver& observer): + AbstractObserver(observer), + _pObject(observer._pObject), + _method(observer._method) + { + } + + ~NObserver() + { + } + + NObserver& operator = (const NObserver& observer) + { + if (&observer != this) + { + _pObject = observer._pObject; + _method = observer._method; + } + return *this; + } + + void notify(Notification* pNf) const + { + Poco::Mutex::ScopedLock lock(_mutex); + + if (_pObject) + { + N* pCastNf = dynamic_cast<N*>(pNf); + if (pCastNf) + { + NotificationPtr ptr(pCastNf, true); + (_pObject->*_method)(ptr); + } + } + } + + bool equals(const AbstractObserver& abstractObserver) const + { + const NObserver* pObs = dynamic_cast<const NObserver*>(&abstractObserver); + return pObs && pObs->_pObject == _pObject && pObs->_method == _method; + } + + bool accepts(Notification* pNf) const + { + return dynamic_cast<N*>(pNf) != 0; + } + + AbstractObserver* clone() const + { + return new NObserver(*this); + } + + void disable() + { + Poco::Mutex::ScopedLock lock(_mutex); + + _pObject = 0; + } + +private: + NObserver(); + + C* _pObject; + Callback _method; + mutable Poco::Mutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NObserver_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedEvent.h b/contrib/libs/poco/Foundation/include/Poco/NamedEvent.h new file mode 100644 index 0000000000..b473be108b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedEvent.h @@ -0,0 +1,96 @@ +// +// NamedEvent.h +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEvent class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedEvent_INCLUDED +#define Foundation_NamedEvent_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/NamedEvent_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/NamedEvent_WIN32.h" +#elif POCO_OS == POCO_OS_ANDROID +#include "Poco/NamedEvent_Android.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/NamedEvent_UNIX.h" +#endif + + +namespace Poco { + + +class Foundation_API NamedEvent: public NamedEventImpl + /// An NamedEvent is a global synchronization object + /// that allows one process or thread to signal an + /// other process or thread that a certain event + /// has happened. + /// + /// Unlike an Event, which itself is the unit of synchronization, + /// a NamedEvent refers to a named operating system resource being the + /// unit of synchronization. + /// In other words, there can be multiple instances of NamedEvent referring + /// to the same actual synchronization object. + /// + /// NamedEvents are always autoresetting. + /// + /// There should not be more than one instance of NamedEvent for + /// a given name in a process. Otherwise, the instances may + /// interfere with each other. +{ +public: + NamedEvent(const std::string& name); + /// Creates the event. + + ~NamedEvent(); + /// Destroys the event. + + void set(); + /// Signals the event. + /// The one thread or process waiting for the event + /// can resume execution. + + void wait(); + /// Waits for the event to become signalled. + +private: + NamedEvent(); + NamedEvent(const NamedEvent&); + NamedEvent& operator = (const NamedEvent&); +}; + + +// +// inlines +// +inline void NamedEvent::set() +{ + setImpl(); +} + + +inline void NamedEvent::wait() +{ + waitImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedEvent_Android.h b/contrib/libs/poco/Foundation/include/Poco/NamedEvent_Android.h new file mode 100644 index 0000000000..910c8a46e0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedEvent_Android.h @@ -0,0 +1,40 @@ +// +// NamedEvent_Android.h +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEventImpl class for Android. +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedEvent_Android_INCLUDED +#define Foundation_NamedEvent_Android_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API NamedEventImpl +{ +protected: + NamedEventImpl(const std::string& name); + ~NamedEventImpl(); + void setImpl(); + void waitImpl(); +}; + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_Android_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedEvent_UNIX.h b/contrib/libs/poco/Foundation/include/Poco/NamedEvent_UNIX.h new file mode 100644 index 0000000000..e593790d65 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedEvent_UNIX.h @@ -0,0 +1,53 @@ +// +// NamedEvent_UNIX.h +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEventImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedEvent_UNIX_INCLUDED +#define Foundation_NamedEvent_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX) +#include <semaphore.h> +#endif + + +namespace Poco { + + +class Foundation_API NamedEventImpl +{ +protected: + NamedEventImpl(const std::string& name); + ~NamedEventImpl(); + void setImpl(); + void waitImpl(); + +private: + std::string getFileName(); + + std::string _name; +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX) + sem_t* _sem; +#else + int _semid; // semaphore id +#endif +}; + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedEvent_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/NamedEvent_WIN32.h new file mode 100644 index 0000000000..4d09f90a8e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedEvent_WIN32.h @@ -0,0 +1,45 @@ +// +// NamedEvent_WIN32.h +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEventImpl class for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedEvent_WIN32_INCLUDED +#define Foundation_NamedEvent_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API NamedEventImpl +{ +protected: + NamedEventImpl(const std::string& name); + ~NamedEventImpl(); + void setImpl(); + void waitImpl(); + +private: + std::string _name; + HANDLE _event; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedEvent_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/NamedEvent_WIN32U.h new file mode 100644 index 0000000000..b2936c416c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedEvent_WIN32U.h @@ -0,0 +1,46 @@ +// +// NamedEvent_WIN32U.h +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEventImpl class for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedEvent_WIN32U_INCLUDED +#define Foundation_NamedEvent_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API NamedEventImpl +{ +protected: + NamedEventImpl(const std::string& name); + ~NamedEventImpl(); + void setImpl(); + void waitImpl(); + +private: + std::string _name; + std::wstring _uname; + HANDLE _event; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedMutex.h b/contrib/libs/poco/Foundation/include/Poco/NamedMutex.h new file mode 100644 index 0000000000..421f018e26 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedMutex.h @@ -0,0 +1,110 @@ +// +// NamedMutex.h +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutex class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedMutex_INCLUDED +#define Foundation_NamedMutex_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ScopedLock.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/NamedMutex_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/NamedMutex_WIN32.h" +#elif POCO_OS == POCO_OS_ANDROID +#include "Poco/NamedMutex_Android.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/NamedMutex_UNIX.h" +#endif + + +namespace Poco { + + +class Foundation_API NamedMutex: private NamedMutexImpl + /// A NamedMutex (mutual exclusion) is a global synchronization + /// mechanism used to control access to a shared resource + /// in a concurrent (multi process) scenario. + /// Using the ScopedLock class is the preferred way to automatically + /// lock and unlock a mutex. + /// + /// Unlike a Mutex or a FastMutex, which itself is the unit of synchronization, + /// a NamedMutex refers to a named operating system resource being the + /// unit of synchronization. + /// In other words, there can be multiple instances of NamedMutex referring + /// to the same actual synchronization object. + /// + /// + /// There should not be more than one instance of NamedMutex for + /// a given name in a process. Otherwise, the instances may + /// interfere with each other. +{ +public: + typedef Poco::ScopedLock<NamedMutex> ScopedLock; + + NamedMutex(const std::string& name); + /// creates the Mutex. + + ~NamedMutex(); + /// destroys the Mutex. + + void lock(); + /// Locks the mutex. Blocks if the mutex + /// is held by another process or thread. + + bool tryLock(); + /// Tries to lock the mutex. Returns false immediately + /// if the mutex is already held by another process or thread. + /// Returns true if the mutex was successfully locked. + + void unlock(); + /// Unlocks the mutex so that it can be acquired by + /// other threads. + +private: + NamedMutex(); + NamedMutex(const NamedMutex&); + NamedMutex& operator = (const NamedMutex&); +}; + + +// +// inlines +// +inline void NamedMutex::lock() +{ + lockImpl(); +} + + +inline bool NamedMutex::tryLock() +{ + return tryLockImpl(); +} + + +inline void NamedMutex::unlock() +{ + unlockImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedMutex_Android.h b/contrib/libs/poco/Foundation/include/Poco/NamedMutex_Android.h new file mode 100644 index 0000000000..c570b86292 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedMutex_Android.h @@ -0,0 +1,41 @@ +// +// NamedMutex_Android.h +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutexImpl class for Android. +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedMutex_Android_INCLUDED +#define Foundation_NamedMutex_Android_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API NamedMutexImpl +{ +protected: + NamedMutexImpl(const std::string& name); + ~NamedMutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); +}; + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_Android_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedMutex_UNIX.h b/contrib/libs/poco/Foundation/include/Poco/NamedMutex_UNIX.h new file mode 100644 index 0000000000..da77a32eef --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedMutex_UNIX.h @@ -0,0 +1,57 @@ +// +// NamedMutex_UNIX.h +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutexImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedMutex_UNIX_INCLUDED +#define Foundation_NamedMutex_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include <sys/types.h> +#include <sys/stat.h> +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX) +#include <semaphore.h> +#endif + + +namespace Poco { + + +class Foundation_API NamedMutexImpl +{ +protected: + NamedMutexImpl(const std::string& name); + ~NamedMutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + std::string getFileName(); + + std::string _name; +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX) + sem_t* _sem; +#else + int _semid; // semaphore id + bool _owned; +#endif +}; + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedMutex_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/NamedMutex_WIN32.h new file mode 100644 index 0000000000..c43dd35345 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedMutex_WIN32.h @@ -0,0 +1,46 @@ +// +// NamedMutex_WIN32.h +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutexImpl class for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedMutex_WIN32_INCLUDED +#define Foundation_NamedMutex_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API NamedMutexImpl +{ +protected: + NamedMutexImpl(const std::string& name); + ~NamedMutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + std::string _name; + HANDLE _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedMutex_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/NamedMutex_WIN32U.h new file mode 100644 index 0000000000..8ee3158658 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedMutex_WIN32U.h @@ -0,0 +1,47 @@ +// +// NamedMutex_WIN32U.h +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutexImpl class for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedMutex_WIN32U_INCLUDED +#define Foundation_NamedMutex_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API NamedMutexImpl +{ +protected: + NamedMutexImpl(const std::string& name); + ~NamedMutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + std::string _name; + std::wstring _uname; + HANDLE _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NamedTuple.h b/contrib/libs/poco/Foundation/include/Poco/NamedTuple.h new file mode 100644 index 0000000000..9a193575d6 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NamedTuple.h @@ -0,0 +1,4462 @@ +// +// NamedTuple.h +// +// Library: Foundation +// Package: Core +// Module: NamedTuple +// +// Definition of the NamedTuple class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NamedTuple_INCLUDED +#define Foundation_NamedTuple_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Tuple.h" +#include "Poco/TypeList.h" +#include "Poco/DynamicAny.h" +#include "Poco/SharedPtr.h" +#include "Poco/Format.h" + + +namespace Poco { + + +template<class T0, + class T1 = NullTypeList, + class T2 = NullTypeList, + class T3 = NullTypeList, + class T4 = NullTypeList, + class T5 = NullTypeList, + class T6 = NullTypeList, + class T7 = NullTypeList, + class T8 = NullTypeList, + class T9 = NullTypeList, + class T10 = NullTypeList, + class T11 = NullTypeList, + class T12 = NullTypeList, + class T13 = NullTypeList, + class T14 = NullTypeList, + class T15 = NullTypeList, + class T16 = NullTypeList, + class T17 = NullTypeList, + class T18 = NullTypeList, + class T19 = NullTypeList> +struct NamedTuple: public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::Type Type; + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17), + typename TypeWrapper<T18>::CONSTTYPE& t18 = POCO_TYPEWRAPPER_DEFAULTVALUE(T18), + typename TypeWrapper<T19>::CONSTTYPE& t19 = POCO_TYPEWRAPPER_DEFAULTVALUE(T19)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18,t19), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17), + typename TypeWrapper<T18>::CONSTTYPE& t18 = POCO_TYPEWRAPPER_DEFAULTVALUE(T18), + typename TypeWrapper<T19>::CONSTTYPE& t19 = POCO_TYPEWRAPPER_DEFAULTVALUE(T19)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18,t19) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + const std::string& n12 = "M", + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + const std::string& n13 = "N", + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + const std::string& n14 = "O", + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + const std::string& n15 = "P", + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + const std::string& n16 = "Q", + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + const std::string& n17 = "R", + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17), + const std::string& n18 = "S", + typename TypeWrapper<T18>::CONSTTYPE& t18 = POCO_TYPEWRAPPER_DEFAULTVALUE(T18), + const std::string& n19 = "T", + typename TypeWrapper<T19>::CONSTTYPE& t19 = POCO_TYPEWRAPPER_DEFAULTVALUE(T19)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18,t19), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14,n15,n16,n17,n18,n19); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + case 12: return TupleType::template get<12>(); + case 13: return TupleType::template get<13>(); + case 14: return TupleType::template get<14>(); + case 15: return TupleType::template get<15>(); + case 16: return TupleType::template get<16>(); + case 17: return TupleType::template get<17>(); + case 18: return TupleType::template get<18>(); + case 19: return TupleType::template get<19>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L", + const std::string& n12 = "M", + const std::string& n13 = "N", + const std::string& n14 = "O", + const std::string& n15 = "P", + const std::string& n16 = "Q", + const std::string& n17 = "R", + const std::string& n18 = "S", + const std::string& n19 = "T") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + _pNames->push_back(n12); + _pNames->push_back(n13); + _pNames->push_back(n14); + _pNames->push_back(n15); + _pNames->push_back(n16); + _pNames->push_back(n17); + _pNames->push_back(n18); + _pNames->push_back(n19); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14, + class T15, + class T16, + class T17, + class T18> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::Type Type; + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17), + typename TypeWrapper<T18>::CONSTTYPE& t18 = POCO_TYPEWRAPPER_DEFAULTVALUE(T18)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17), + typename TypeWrapper<T18>::CONSTTYPE& t18 = POCO_TYPEWRAPPER_DEFAULTVALUE(T18)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + const std::string& n12 = "M", + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + const std::string& n13 = "N", + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + const std::string& n14 = "O", + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + const std::string& n15 = "P", + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + const std::string& n16 = "Q", + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + const std::string& n17 = "R", + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17), + const std::string& n18 = "S", + typename TypeWrapper<T18>::CONSTTYPE& t18 = POCO_TYPEWRAPPER_DEFAULTVALUE(T18)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14,n15,n16,n17,n18); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + case 12: return TupleType::template get<12>(); + case 13: return TupleType::template get<13>(); + case 14: return TupleType::template get<14>(); + case 15: return TupleType::template get<15>(); + case 16: return TupleType::template get<16>(); + case 17: return TupleType::template get<17>(); + case 18: return TupleType::template get<18>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L", + const std::string& n12 = "M", + const std::string& n13 = "N", + const std::string& n14 = "O", + const std::string& n15 = "P", + const std::string& n16 = "Q", + const std::string& n17 = "R", + const std::string& n18 = "S") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + _pNames->push_back(n12); + _pNames->push_back(n13); + _pNames->push_back(n14); + _pNames->push_back(n15); + _pNames->push_back(n16); + _pNames->push_back(n17); + _pNames->push_back(n18); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14, + class T15, + class T16, + class T17> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::Type Type; + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + const std::string& n12 = "M", + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + const std::string& n13 = "N", + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + const std::string& n14 = "O", + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + const std::string& n15 = "P", + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + const std::string& n16 = "Q", + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + const std::string& n17 = "R", + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14,n15,n16,n17); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + case 12: return TupleType::template get<12>(); + case 13: return TupleType::template get<13>(); + case 14: return TupleType::template get<14>(); + case 15: return TupleType::template get<15>(); + case 16: return TupleType::template get<16>(); + case 17: return TupleType::template get<17>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L", + const std::string& n12 = "M", + const std::string& n13 = "N", + const std::string& n14 = "O", + const std::string& n15 = "P", + const std::string& n16 = "Q", + const std::string& n17 = "R") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + _pNames->push_back(n12); + _pNames->push_back(n13); + _pNames->push_back(n14); + _pNames->push_back(n15); + _pNames->push_back(n16); + _pNames->push_back(n17); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14, + class T15, + class T16> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::Type Type; + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + const std::string& n12 = "M", + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + const std::string& n13 = "N", + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + const std::string& n14 = "O", + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + const std::string& n15 = "P", + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + const std::string& n16 = "Q", + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14,n15,n16); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + case 12: return TupleType::template get<12>(); + case 13: return TupleType::template get<13>(); + case 14: return TupleType::template get<14>(); + case 15: return TupleType::template get<15>(); + case 16: return TupleType::template get<16>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L", + const std::string& n12 = "M", + const std::string& n13 = "N", + const std::string& n14 = "O", + const std::string& n15 = "P", + const std::string& n16 = "Q") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + _pNames->push_back(n12); + _pNames->push_back(n13); + _pNames->push_back(n14); + _pNames->push_back(n15); + _pNames->push_back(n16); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14, + class T15> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + const std::string& n12 = "M", + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + const std::string& n13 = "N", + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + const std::string& n14 = "O", + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + const std::string& n15 = "P", + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14,n15); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + case 12: return TupleType::template get<12>(); + case 13: return TupleType::template get<13>(); + case 14: return TupleType::template get<14>(); + case 15: return TupleType::template get<15>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L", + const std::string& n12 = "M", + const std::string& n13 = "N", + const std::string& n14 = "O", + const std::string& n15 = "P") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + _pNames->push_back(n12); + _pNames->push_back(n13); + _pNames->push_back(n14); + _pNames->push_back(n15); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + const std::string& n12 = "M", + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + const std::string& n13 = "N", + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + const std::string& n14 = "O", + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + case 12: return TupleType::template get<12>(); + case 13: return TupleType::template get<13>(); + case 14: return TupleType::template get<14>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L", + const std::string& n12 = "M", + const std::string& n13 = "N", + const std::string& n14 = "O") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + _pNames->push_back(n12); + _pNames->push_back(n13); + _pNames->push_back(n14); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + const std::string& n12 = "M", + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + const std::string& n13 = "N", + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + case 12: return TupleType::template get<12>(); + case 13: return TupleType::template get<13>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L", + const std::string& n12 = "M", + const std::string& n13 = "N") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + _pNames->push_back(n12); + _pNames->push_back(n13); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + const std::string& n12 = "M", + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12), _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + case 12: return TupleType::template get<12>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L", + const std::string& n12 = "M") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + _pNames->push_back(n12); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + const std::string& n11 = "L", + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + case 11: return TupleType::template get<11>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K", + const std::string& n11 = "L") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + _pNames->push_back(n11); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + const std::string& n10 = "K", + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10), _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + case 10: return TupleType::template get<10>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J", + const std::string& n10 = "K") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + _pNames->push_back(n10); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + const std::string& n9 = "J", + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8,t9), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8,n9); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + case 9: return TupleType::template get<9>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I", + const std::string& n9 = "J") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + _pNames->push_back(n9); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + const std::string& n8 = "I", + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7,t8), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7,n8); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + case 8: return TupleType::template get<8>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H", + const std::string& n8 = "I") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + _pNames->push_back(n8); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,T7,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6,T7> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6,T7> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6,T7>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + const std::string& n7 = "H", + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7)): + TupleType(t0,t1,t2,t3,t4,t5,t6,t7), + _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6,n7); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + case 7: return TupleType::template get<7>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G", + const std::string& n7 = "H") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + _pNames->push_back(n7); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6> +struct NamedTuple<T0,T1,T2,T3,T4,T5,T6,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5,T6> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5,T6> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5,T6>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6)): + TupleType(t0,t1,t2,t3,t4,t5,t6), _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6)): + TupleType(t0,t1,t2,t3,t4,t5,t6) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + const std::string& n6 = "G", + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6)): + TupleType(t0,t1,t2,t3,t4,t5,t6), _pNames(0) + { + init(n0,n1,n2,n3,n4,n5,n6); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + case 6: return TupleType::template get<6>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F", + const std::string& n6 = "G") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + _pNames->push_back(n6); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4, + class T5> +struct NamedTuple<T0,T1,T2,T3,T4,T5,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4,T5> +{ + typedef Tuple<T0,T1,T2,T3,T4,T5> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4,T5>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5)): + TupleType(t0,t1,t2,t3,t4,t5), _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5)): + TupleType(t0,t1,t2,t3,t4,t5) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + const std::string& n5 = "F", + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5)): + TupleType(t0,t1,t2,t3,t4,t5), _pNames(0) + { + init(n0,n1,n2,n3,n4,n5); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + case 5: return TupleType::template get<5>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E", + const std::string& n5 = "F") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + _pNames->push_back(n5); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3, + class T4> +struct NamedTuple<T0,T1,T2,T3,T4,NullTypeList>: + public Tuple<T0,T1,T2,T3,T4> +{ + typedef Tuple<T0,T1,T2,T3,T4> TupleType; + typedef typename Tuple<T0,T1,T2,T3,T4>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4)): + TupleType(t0,t1,t2,t3,t4), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4)): + TupleType(t0,t1,t2,t3,t4) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + const std::string& n4 = "E", + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4)): + TupleType(t0,t1,t2,t3,t4), + _pNames(0) + { + init(n0,n1,n2,n3,n4); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + case 4: return TupleType::template get<4>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D", + const std::string& n4 = "E") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + _pNames->push_back(n4); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2, + class T3> +struct NamedTuple<T0,T1,T2,T3,NullTypeList>: + public Tuple<T0,T1,T2,T3> +{ + typedef Tuple<T0,T1,T2,T3> TupleType; + typedef typename Tuple<T0,T1,T2,T3>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3)): + TupleType(t0,t1,t2,t3), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3)): + TupleType(t0,t1,t2,t3) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + const std::string& n3 = "D", + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3)): + TupleType(t0,t1,t2,t3), _pNames(0) + { + init(n0,n1,n2,n3); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + case 3: return TupleType::template get<3>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C", + const std::string& n3 = "D") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + _pNames->push_back(n3); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1, + class T2> +struct NamedTuple<T0,T1,T2,NullTypeList>: + public Tuple<T0,T1,T2> +{ + typedef Tuple<T0,T1,T2> TupleType; + typedef typename Tuple<T0,T1,T2>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2)): + TupleType(t0,t1,t2), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2)): + TupleType(t0,t1,t2) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + const std::string& n2 = "C", + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2)): + TupleType(t0,t1,t2), + _pNames(0) + { + init(n0,n1,n2); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + case 2: return TupleType::template get<2>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B", + const std::string& n2 = "C") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + _pNames->push_back(n2); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0, + class T1> +struct NamedTuple<T0,T1,NullTypeList>: + public Tuple<T0,T1> +{ + typedef Tuple<T0,T1> TupleType; + typedef typename Tuple<T0,T1>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1)): + TupleType(t0,t1), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1)): + TupleType(t0,t1) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, + typename TypeWrapper<T0>::CONSTTYPE& t0, + const std::string& n1 = "B", + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1)): + TupleType(t0,t1), + _pNames(0) + { + init(n0,n1); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + case 1: return TupleType::template get<1>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A", + const std::string& n1 = "B") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + _pNames->push_back(n1); + } + } + + NameVecPtr _pNames; +}; + + +template<class T0> +struct NamedTuple<T0,NullTypeList>: + public Tuple<T0> +{ + typedef Tuple<T0> TupleType; + typedef typename Tuple<T0>::Type Type; + + typedef std::vector<std::string> NameVec; + typedef SharedPtr<NameVec> NameVecPtr; + + NamedTuple(): _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(typename TypeWrapper<T0>::CONSTTYPE& t0): + TupleType(t0), + _pNames(0) + { + init(); + } + + NamedTuple(const NameVecPtr& rNames, + typename TypeWrapper<T0>::CONSTTYPE& t0): + TupleType(t0) + { + if (rNames->size() != TupleType::length) + throw InvalidArgumentException("Wrong names vector length."); + + _pNames = rNames; + } + + NamedTuple(const std::string& n0, typename TypeWrapper<T0>::CONSTTYPE& t0): + TupleType(t0), + _pNames(0) + { + init(n0); + } + + const DynamicAny get(const std::string& name) const + { + NameVec::const_iterator it = _pNames->begin(); + NameVec::const_iterator itEnd = _pNames->end(); + + for(std::size_t counter = 0; it != itEnd; ++it, ++counter) + { + if (name == *it) + { + switch (counter) + { + case 0: return TupleType::template get<0>(); + default: throw RangeException(); + } + } + } + + throw NotFoundException("Name not found: " + name); + } + + const DynamicAny operator [] (const std::string& name) const + { + return get(name); + } + + template<int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return TupleType::template get<N>(); + } + + template<int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return TupleType::template get<N>(); + } + + template<int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + return TupleType::template set<N>(val); + } + + const NameVecPtr& names() + { + return _pNames; + } + + void setName(std::size_t index, const std::string& name) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + (*_pNames)[index] = name; + } + + const std::string& getName(std::size_t index) + { + if (index >= _pNames->size()) + throw InvalidArgumentException(format("Invalid index: %z", index)); + + return (*_pNames)[index]; + } + + bool operator == (const NamedTuple& other) const + { + return TupleType(*this) == TupleType(other) && _pNames == other._pNames; + } + + bool operator != (const NamedTuple& other) const + { + return !(*this == other); + } + + bool operator < (const NamedTuple& other) const + { + TupleType th(*this); + TupleType oth(other); + + return (th < oth && _pNames == other._pNames) || + (th == oth && _pNames < other._pNames) || + (th < oth && _pNames < other._pNames); + } + +private: + void init(const std::string& n0 = "A") + { + if (!_pNames) + { + _pNames = new NameVec; + _pNames->push_back(n0); + } + } + + NameVecPtr _pNames; +}; + + +} // namespace Poco + + +#endif // Foundation_Tuple_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NestedDiagnosticContext.h b/contrib/libs/poco/Foundation/include/Poco/NestedDiagnosticContext.h new file mode 100644 index 0000000000..ccb29a56a9 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NestedDiagnosticContext.h @@ -0,0 +1,181 @@ +// +// NestedDiagnosticContext.h +// +// Library: Foundation +// Package: Core +// Module: NestedDiagnosticContext +// +// Definition of the NestedDiagnosticContext class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NestedDiagnosticContext_INCLUDED +#define Foundation_NestedDiagnosticContext_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> +#include <ostream> + + +namespace Poco { + + +class NDCScope; + + +class Foundation_API NestedDiagnosticContext + /// This class implements a Nested Diagnostic Context (NDC), + /// as described in Neil Harrison's article "Patterns for Logging + /// Diagnostic Messages" in "Pattern Languages of Program Design 3" + /// (Addison-Wesley). + /// + /// A NDC maintains a stack of context information, consisting of + /// an informational string (e.g., a method name), as well as an + /// optional source code line number and file name. + /// NDCs are especially useful for tagging log messages with + /// context information which is very helpful in a multithreaded + /// server scenario. + /// Every thread has its own private NDC, which is automatically + /// created when needed and destroyed when the thread terminates. + /// + /// The NDCScope (or NDC::Scope) class can be used to automatically + /// push information at the beginning of a scope, and to pop it + /// at the end. + /// The poco_ndc(info) macro augments the information with a + /// source code line number and file name. +{ +public: + typedef NDCScope Scope; + + NestedDiagnosticContext(); + /// Creates the NestedDiagnosticContext. + + NestedDiagnosticContext(const NestedDiagnosticContext& ctx); + /// Copy constructor. + + ~NestedDiagnosticContext(); + /// Destroys the NestedDiagnosticContext. + + NestedDiagnosticContext& operator = (const NestedDiagnosticContext& ctx); + /// Assignment operator. + + void push(const std::string& info); + /// Pushes a context (without line number and filename) onto the stack. + + void push(const std::string& info, int line, const char* filename); + /// Pushes a context (including line number and filename) + /// onto the stack. Filename must be a static string, such as the + /// one produced by the __FILE__ preprocessor macro. + + void pop(); + /// Pops the top-most context off the stack. + + int depth() const; + /// Returns the depth (number of contexts) of the stack. + + std::string toString() const; + /// Returns the stack as a string with entries + /// delimited by colons. The string does not contain + /// line numbers and filenames. + + void dump(std::ostream& ostr) const; + /// Dumps the stack (including line number and filenames) + /// to the given stream. The entries are delimited by + /// a newline. + + void dump(std::ostream& ostr, const std::string& delimiter) const; + /// Dumps the stack (including line number and filenames) + /// to the given stream. + + void clear(); + /// Clears the NDC stack. + + static NestedDiagnosticContext& current(); + /// Returns the current thread's NDC. + +private: + struct Context + { + std::string info; + const char* file; + int line; + }; + typedef std::vector<Context> Stack; + + Stack _stack; +}; + + +typedef NestedDiagnosticContext NDC; + + +class Foundation_API NDCScope + /// This class can be used to automatically push a context onto + /// the NDC stack at the beginning of a scope, and to pop + /// the context at the end of the scope. +{ +public: + NDCScope(const std::string& info); + /// Pushes a context on the stack. + + NDCScope(const std::string& info, int line, const char* filename); + /// Pushes a context on the stack. + + ~NDCScope(); + /// Pops the top-most context off the stack. +}; + + +// +// inlines +// +inline NDCScope::NDCScope(const std::string& info) +{ + NestedDiagnosticContext::current().push(info); +} + + +inline NDCScope::NDCScope(const std::string& info, int line, const char* filename) +{ + NestedDiagnosticContext::current().push(info, line, filename); +} + + +inline NDCScope::~NDCScope() +{ + try + { + NestedDiagnosticContext::current().pop(); + } + catch (...) + { + poco_unexpected(); + } +} + + +// +// helper macros +// +#define poco_ndc(func) \ + Poco::NDCScope _theNdcScope(#func, __LINE__, __FILE__) + + +#if defined(_DEBUG) + #define poco_ndc_dbg(func) \ + Poco::NDCScope _theNdcScope(#func, __LINE__, __FILE__) +#else + #define poco_ndc_dbg(func) +#endif + + +} // namespace Poco + + +#endif // Foundation_NestedDiagnosticContext_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Notification.h b/contrib/libs/poco/Foundation/include/Poco/Notification.h new file mode 100644 index 0000000000..f5f20a1ccd --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Notification.h @@ -0,0 +1,55 @@ +// +// Notification.h +// +// Library: Foundation +// Package: Notifications +// Module: Notification +// +// Definition of the Notification class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Notification_INCLUDED +#define Foundation_Notification_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/RefCountedObject.h" +#include "Poco/AutoPtr.h" + + +namespace Poco { + + +class Foundation_API Notification: public RefCountedObject + /// The base class for all notification classes used + /// with the NotificationCenter and the NotificationQueue + /// classes. + /// The Notification class can be used with the AutoPtr + /// template class. +{ +public: + typedef AutoPtr<Notification> Ptr; + + Notification(); + /// Creates the notification. + + virtual std::string name() const; + /// Returns the name of the notification. + /// The default implementation returns the class name. + +protected: + virtual ~Notification(); +}; + + +} // namespace Poco + + +#endif // Foundation_Notification_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NotificationCenter.h b/contrib/libs/poco/Foundation/include/Poco/NotificationCenter.h new file mode 100644 index 0000000000..411bba8944 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NotificationCenter.h @@ -0,0 +1,139 @@ +// +// NotificationCenter.h +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Definition of the NotificationCenter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NotificationCenter_INCLUDED +#define Foundation_NotificationCenter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Notification.h" +#include "Poco/Mutex.h" +#include "Poco/SharedPtr.h" +#include <vector> +#include <cstddef> + + +namespace Poco { + + +class AbstractObserver; + + +class Foundation_API NotificationCenter + /// A NotificationCenter is essentially a notification dispatcher. + /// It notifies all observers of notifications meeting specific criteria. + /// This information is encapsulated in Notification objects. + /// Client objects register themselves with the notification center as observers of + /// specific notifications posted by other objects. When an event occurs, an object + /// posts an appropriate notification to the notification center. The notification + /// center invokes the registered method on each matching observer, passing the notification + /// as argument. + /// + /// The order in which observers receive notifications is undefined. + /// It is possible for the posting object and the observing object to be the same. + /// The NotificationCenter delivers notifications to observers synchronously. + /// In other words the postNotification() method does not return until all observers have + /// received and processed the notification. + /// If an observer throws an exception while handling a notification, the NotificationCenter + /// stops dispatching the notification and postNotification() rethrows the exception. + /// + /// In a multithreaded scenario, notifications are always delivered in the thread in which the + /// notification was posted, which may not be the same thread in which an observer registered itself. + /// + /// The NotificationCenter class is basically a C++ implementation of the NSNotificationCenter class + /// found in Apple's Cocoa (or OpenStep). + /// + /// While handling a notification, an observer can unregister itself from the notification center, + /// or it can register or unregister other observers. Observers added during a dispatch cycle + /// will not receive the current notification. + /// + /// The method receiving the notification must be implemented as + /// void handleNotification(MyNotification* pNf); + /// The handler method gets co-ownership of the Notification object + /// and must release it when done. This is best done with an AutoPtr: + /// void MyClass::handleNotification(MyNotification* pNf) + /// { + /// AutoPtr<MyNotification> nf(pNf); + /// ... + /// } + /// + /// Alternatively, the NObserver class template can be used to register a callback + /// method. In this case, the callback method receives the Notification in an + /// AutoPtr and thus does not have to deal with object ownership issues: + /// void MyClass::handleNotification(const AutoPtr<MyNotification>& pNf) + /// { + /// ... + /// } +{ +public: + NotificationCenter(); + /// Creates the NotificationCenter. + + ~NotificationCenter(); + /// Destroys the NotificationCenter. + + void addObserver(const AbstractObserver& observer); + /// Registers an observer with the NotificationCenter. + /// Usage: + /// Observer<MyClass, MyNotification> obs(*this, &MyClass::handleNotification); + /// notificationCenter.addObserver(obs); + /// + /// Alternatively, the NObserver template class can be used instead of Observer. + + void removeObserver(const AbstractObserver& observer); + /// Unregisters an observer with the NotificationCenter. + + bool hasObserver(const AbstractObserver& observer) const; + /// Returns true if the observer is registered with this NotificationCenter. + + void postNotification(Notification::Ptr pNotification); + /// Posts a notification to the NotificationCenter. + /// The NotificationCenter then delivers the notification + /// to all interested observers. + /// If an observer throws an exception, dispatching terminates + /// and the exception is rethrown to the caller. + /// Ownership of the notification object is claimed and the + /// notification is released before returning. Therefore, + /// a call like + /// notificationCenter.postNotification(new MyNotification); + /// does not result in a memory leak. + + bool hasObservers() const; + /// Returns true iff there is at least one registered observer. + /// + /// Can be used to improve performance if an expensive notification + /// shall only be created and posted if there are any observers. + + std::size_t countObservers() const; + /// Returns the number of registered observers. + + static NotificationCenter& defaultCenter(); + /// Returns a reference to the default + /// NotificationCenter. + +private: + typedef SharedPtr<AbstractObserver> AbstractObserverPtr; + typedef std::vector<AbstractObserverPtr> ObserverList; + + ObserverList _observers; + mutable Mutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NotificationCenter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NotificationQueue.h b/contrib/libs/poco/Foundation/include/Poco/NotificationQueue.h new file mode 100644 index 0000000000..3194dddd4d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NotificationQueue.h @@ -0,0 +1,155 @@ +// +// NotificationQueue.h +// +// Library: Foundation +// Package: Notifications +// Module: NotificationQueue +// +// Definition of the NotificationQueue class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NotificationQueue_INCLUDED +#define Foundation_NotificationQueue_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Notification.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" +#include <deque> + + +namespace Poco { + + +class NotificationCenter; + + +class Foundation_API NotificationQueue + /// A NotificationQueue object provides a way to implement asynchronous + /// notifications. This is especially useful for sending notifications + /// from one thread to another, for example from a background thread to + /// the main (user interface) thread. + /// + /// The NotificationQueue can also be used to distribute work from + /// a controlling thread to one or more worker threads. Each worker thread + /// repeatedly calls waitDequeueNotification() and processes the + /// returned notification. Special care must be taken when shutting + /// down a queue with worker threads waiting for notifications. + /// The recommended sequence to shut down and destroy the queue is to + /// 1. set a termination flag for every worker thread + /// 2. call the wakeUpAll() method + /// 3. join each worker thread + /// 4. destroy the notification queue. +{ +public: + NotificationQueue(); + /// Creates the NotificationQueue. + + ~NotificationQueue(); + /// Destroys the NotificationQueue. + + void enqueueNotification(Notification::Ptr pNotification); + /// Enqueues the given notification by adding it to + /// the end of the queue (FIFO). + /// The queue takes ownership of the notification, thus + /// a call like + /// notificationQueue.enqueueNotification(new MyNotification); + /// does not result in a memory leak. + + void enqueueUrgentNotification(Notification::Ptr pNotification); + /// Enqueues the given notification by adding it to + /// the front of the queue (LIFO). The event therefore gets processed + /// before all other events already in the queue. + /// The queue takes ownership of the notification, thus + /// a call like + /// notificationQueue.enqueueUrgentNotification(new MyNotification); + /// does not result in a memory leak. + + Notification* dequeueNotification(); + /// Dequeues the next pending notification. + /// Returns 0 (null) if no notification is available. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + Notification* waitDequeueNotification(); + /// Dequeues the next pending notification. + /// If no notification is available, waits for a notification + /// to be enqueued. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// This method returns 0 (null) if wakeUpWaitingThreads() + /// has been called by another thread. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + Notification* waitDequeueNotification(long milliseconds); + /// Dequeues the next pending notification. + /// If no notification is available, waits for a notification + /// to be enqueued up to the specified time. + /// Returns 0 (null) if no notification is available. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + void dispatch(NotificationCenter& notificationCenter); + /// Dispatches all queued notifications to the given + /// notification center. + + void wakeUpAll(); + /// Wakes up all threads that wait for a notification. + + bool empty() const; + /// Returns true iff the queue is empty. + + int size() const; + /// Returns the number of notifications in the queue. + + void clear(); + /// Removes all notifications from the queue. + + bool hasIdleThreads() const; + /// Returns true if the queue has at least one thread waiting + /// for a notification. + + static NotificationQueue& defaultQueue(); + /// Returns a reference to the default + /// NotificationQueue. + +protected: + Notification::Ptr dequeueOne(); + +private: + typedef std::deque<Notification::Ptr> NfQueue; + struct WaitInfo + { + Notification::Ptr pNf; + Event nfAvailable; + }; + typedef std::deque<WaitInfo*> WaitQueue; + + NfQueue _nfQueue; + WaitQueue _waitQueue; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NotificationQueue_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NotificationStrategy.h b/contrib/libs/poco/Foundation/include/Poco/NotificationStrategy.h new file mode 100644 index 0000000000..d36fbe28b0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NotificationStrategy.h @@ -0,0 +1,112 @@ +// +// NotificationStrategy.h +// +// Library: Foundation +// Package: Events +// Module: NotificationStrategy +// +// Definition of the NotificationStrategy interface. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NotificationStrategy_INCLUDED +#define Foundation_NotificationStrategy_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template <class TArgs, class TDelegate> +class NotificationStrategy + /// The interface that all notification strategies must implement. + /// + /// Note: Event is based on policy-driven design, so every strategy implementation + /// must provide all the methods from this interface (otherwise: compile errors) + /// but does not need to inherit from NotificationStrategy. +{ +public: + typedef TDelegate* DelegateHandle; + + NotificationStrategy() + { + } + + virtual ~NotificationStrategy() + { + } + + virtual void notify(const void* sender, TArgs& arguments) = 0; + /// Sends a notification to all registered delegates. + + virtual DelegateHandle add(const TDelegate& delegate) = 0; + /// Adds a delegate to the strategy. + + virtual void remove(const TDelegate& delegate) = 0; + /// Removes a delegate from the strategy, if found. + /// Does nothing if the delegate has not been added. + + virtual void remove(DelegateHandle delegateHandle) = 0; + /// Removes a delegate from the strategy, if found. + /// Does nothing if the delegate has not been added. + + virtual void clear() = 0; + /// Removes all delegates from the strategy. + + virtual bool empty() const = 0; + /// Returns false if the strategy contains at least one delegate. +}; + + +template <class TDelegate> +class NotificationStrategy<void, TDelegate> + /// The interface that all notification strategies must implement. + /// + /// Note: Event is based on policy-driven design, so every strategy implementation + /// must provide all the methods from this interface (otherwise: compile errors) + /// but does not need to inherit from NotificationStrategy. +{ +public: + typedef TDelegate* DelegateHandle; + + NotificationStrategy() + { + } + + virtual ~NotificationStrategy() + { + } + + virtual void notify(const void* sender) = 0; + /// Sends a notification to all registered delegates. + + virtual DelegateHandle add(const TDelegate& delegate) = 0; + /// Adds a delegate to the strategy. + + virtual void remove(const TDelegate& delegate) = 0; + /// Removes a delegate from the strategy, if found. + /// Does nothing if the delegate has not been added. + + virtual void remove(DelegateHandle delegateHandle) = 0; + /// Removes a delegate from the strategy, if found. + /// Does nothing if the delegate has not been added. + + virtual void clear() = 0; + /// Removes all delegates from the strategy. + + virtual bool empty() const = 0; + /// Returns false if the strategy contains at least one delegate. +}; + + +} // namespace Poco + + +#endif // Foundation_NotificationStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NullChannel.h b/contrib/libs/poco/Foundation/include/Poco/NullChannel.h new file mode 100644 index 0000000000..8384dcf4b6 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NullChannel.h @@ -0,0 +1,55 @@ +// +// NullChannel.h +// +// Library: Foundation +// Package: Logging +// Module: NullChannel +// +// Definition of the NullChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NullChannel_INCLUDED +#define Foundation_NullChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" + + +namespace Poco { + + +class Foundation_API NullChannel: public Channel + /// The NullChannel is the /dev/null of Channels. + /// + /// A NullChannel discards all information sent to it. + /// Furthermore, its setProperty() method ignores + /// all properties, so it the NullChannel has the + /// nice feature that it can stand in for any + /// other channel class in a logging configuration. +{ +public: + NullChannel(); + /// Creates the NullChannel. + + ~NullChannel(); + /// Destroys the NullChannel. + + void log(const Message& msg); + /// Does nothing. + + void setProperty(const std::string& name, const std::string& value); + /// Ignores both name and value. +}; + + +} // namespace Poco + + +#endif // Foundation_NullChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NullStream.h b/contrib/libs/poco/Foundation/include/Poco/NullStream.h new file mode 100644 index 0000000000..52c292dff5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NullStream.h @@ -0,0 +1,90 @@ +// +// NullStream.h +// +// Library: Foundation +// Package: Streams +// Module: NullStream +// +// Definition of the NullStreamBuf, NullInputStream and NullOutputStream classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NullStream_INCLUDED +#define Foundation_NullStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API NullStreamBuf: public UnbufferedStreamBuf + /// This stream buffer discards all characters written to it. + /// Any read operation immediately yields EOF. +{ +public: + NullStreamBuf(); + /// Creates a NullStreamBuf. + + ~NullStreamBuf(); + /// Destroys the NullStreamBuf. + +protected: + int readFromDevice(); + int writeToDevice(char c); +}; + + +class Foundation_API NullIOS: public virtual std::ios + /// The base class for NullInputStream and NullOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + NullIOS(); + ~NullIOS(); + +protected: + NullStreamBuf _buf; +}; + + +class Foundation_API NullInputStream: public NullIOS, public std::istream + /// Any read operation from this stream immediately + /// yields EOF. +{ +public: + NullInputStream(); + /// Creates the NullInputStream. + + ~NullInputStream(); + /// Destroys the NullInputStream. +}; + + +class Foundation_API NullOutputStream: public NullIOS, public std::ostream + /// This stream discards all characters written to it. +{ +public: + NullOutputStream(); + /// Creates the NullOutputStream. + + ~NullOutputStream(); + /// Destroys the NullOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_NullStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Nullable.h b/contrib/libs/poco/Foundation/include/Poco/Nullable.h new file mode 100644 index 0000000000..d113256cf2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Nullable.h @@ -0,0 +1,323 @@ +// +// Nullable.h +// +// Library: Foundation +// Package: Core +// Module: Nullable +// +// Definition of the Nullable template class. +// +// Copyright (c) 2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Nullable_INCLUDED +#define Foundation_Nullable_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <algorithm> +#include <iostream> + + +namespace Poco { + + +enum NullType +{ + NULL_GENERIC = 0 +}; + + +template <typename C> +class Nullable + /// Nullable is a simple wrapper class for value types + /// that allows objects or native type variables + /// to have "null" value. + /// + /// The class is useful for passing parameters to functions + /// when parameters are optional and no default values + /// should be used or when a non-assigned state is needed, + /// such as in e.g. fetching null values from database. + /// + /// A Nullable can be default constructed. In this case, + /// the Nullable will have a Null value and isNull() will + /// return true. Calling value() (without default value) on + /// a Null object will throw a NullValueException. + /// + /// A Nullable can also be constructed from a value. + /// It is possible to assign a value to a Nullable, and + /// to reset a Nullable to contain a Null value by calling + /// clear(). + /// + /// For use with Nullable, the value type should support + /// default construction. +{ +public: + Nullable(): + /// Creates an empty Nullable. + _value(), + _isNull(true), + _null() + { + } + + Nullable(const NullType&): + /// Creates an empty Nullable. + _value(), + _isNull(true), + _null() + { + } + + Nullable(const C& value): + /// Creates a Nullable with the given value. + _value(value), + _isNull(false), + _null() + { + } + + Nullable(const Nullable& other): + /// Creates a Nullable by copying another one. + _value(other._value), + _isNull(other._isNull), + _null() + { + } + + ~Nullable() + /// Destroys the Nullable. + { + } + + Nullable& assign(const C& value) + /// Assigns a value to the Nullable. + { + _value = value; + _isNull = false; + return *this; + } + + Nullable& assign(const Nullable& other) + /// Assigns another Nullable. + { + Nullable tmp(other); + swap(tmp); + return *this; + } + + Nullable& assign(NullType) + /// Sets value to null. + { + _isNull = true; + return *this; + } + + Nullable& operator = (const C& value) + /// Assigns a value to the Nullable. + { + return assign(value); + } + + Nullable& operator = (const Nullable& other) + /// Assigns another Nullable. + { + return assign(other); + } + + Nullable& operator = (NullType) + /// Assigns another Nullable. + { + _isNull = true; + return *this; + } + + void swap(Nullable& other) + /// Swaps this Nullable with other. + { + std::swap(_value, other._value); + std::swap(_isNull, other._isNull); + } + + bool operator == (const Nullable<C>& other) const + /// Compares two Nullables for equality + { + return (_isNull && other._isNull) || (_isNull == other._isNull && _value == other._value); + } + + bool operator == (const C& value) const + /// Compares Nullable with value for equality + { + return (!_isNull && _value == value); + } + + bool operator == (const NullType&) const + /// Compares Nullable with NullData for equality + { + return _isNull; + } + + bool operator != (const C& value) const + /// Compares Nullable with value for non equality + { + return !(*this == value); + } + + bool operator != (const Nullable<C>& other) const + /// Compares two Nullables for non equality + { + return !(*this == other); + } + + bool operator != (const NullType&) const + /// Compares with NullData for non equality + { + return !_isNull; + } + + bool operator < (const Nullable<C>& other) const + /// Compares two Nullable objects. Return true if this object's + /// value is smaler than the other object's value. + /// Null value is smaller than a non-null value. + { + if (_isNull && other._isNull) return false; + + if (!_isNull && !other._isNull) + return (_value < other._value); + + if (_isNull && !other._isNull) return true; + + return false; + } + + bool operator > (const Nullable<C>& other) const + /// Compares two Nullable objects. Return true if this object's + /// value is greater than the other object's value. + /// A non-null value is greater than a null value. + { + return !(*this == other) && !(*this < other); + } + + C& value() + /// Returns the Nullable's value. + /// + /// Throws a NullValueException if the Nullable is empty. + { + if (!_isNull) + return _value; + else + throw NullValueException(); + } + + const C& value() const + /// Returns the Nullable's value. + /// + /// Throws a NullValueException if the Nullable is empty. + { + if (!_isNull) + return _value; + else + throw NullValueException(); + } + + const C& value(const C& deflt) const + /// Returns the Nullable's value, or the + /// given default value if the Nullable is empty. + { + return _isNull ? deflt : _value; + } + + operator C& () + /// Get reference to the value + { + return value(); + } + + operator const C& () const + /// Get const reference to the value + { + return value(); + } + + operator NullType& () + /// Get reference to the value + { + + return _null; + } + + bool isNull() const + /// Returns true if the Nullable is empty. + { + return _isNull; + } + + void clear() + /// Clears the Nullable. + { + _isNull = true; + } + +private: + C _value; + bool _isNull; + NullType _null; +}; + + +template <typename C> +inline void swap(Nullable<C>& n1, Nullable<C>& n2) +{ + n1.swap(n2); +} + + +template <typename C> +std::ostream& operator<<(std::ostream& out, const Nullable<C>& obj) +{ + if (!obj.isNull()) out << obj.value(); + return out; +} + + +template <typename C> +bool operator == (const NullType&, const Nullable<C>& n) + /// Returns true if this Nullable is null. +{ + return n.isNull(); +} + + +template <typename C> +bool operator != (const C& c, const Nullable<C>& n) + /// Compares Nullable with value for non equality +{ + return !(n == c); +} + + +template <typename C> +bool operator == (const C& c, const Nullable<C>& n) + /// Compares Nullable with NullData for equality +{ + return (n == c); +} + + +template <typename C> +bool operator != (const NullType&, const Nullable<C>& n) + /// Returns true if this Nullable is not null. +{ + return !n.isNull(); +} + + +} // namespace Poco + + +#endif // Foundation_Nullable_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NumberFormatter.h b/contrib/libs/poco/Foundation/include/Poco/NumberFormatter.h new file mode 100644 index 0000000000..ff8d13c465 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NumberFormatter.h @@ -0,0 +1,907 @@ +// +// NumberFormatter.h +// +// Library: Foundation +// Package: Core +// Module: NumberFormatter +// +// Definition of the NumberFormatter class. +// +// Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NumberFormatter_INCLUDED +#define Foundation_NumberFormatter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/NumericString.h" + + +namespace Poco { + + +class Foundation_API NumberFormatter + /// The NumberFormatter class provides static methods + /// for formatting numeric values into strings. + /// + /// There are two kind of static member functions: + /// * format* functions return a std::string containing + /// the formatted value. + /// * append* functions append the formatted value to + /// an existing string. +{ +public: + enum BoolFormat + { + FMT_TRUE_FALSE, + FMT_YES_NO, + FMT_ON_OFF + }; + + static const unsigned NF_MAX_INT_STRING_LEN = 32; // increase for 64-bit binary formatting support + static const unsigned NF_MAX_FLT_STRING_LEN = POCO_MAX_FLT_STRING_LEN; + + static std::string format(int value); + /// Formats an integer value in decimal notation. + + static std::string format(int value, int width); + /// Formats an integer value in decimal notation, + /// right justified in a field having at least + /// the specified width. + + static std::string format0(int value, int width); + /// Formats an integer value in decimal notation, + /// right justified and zero-padded in a field + /// having at least the specified width. + + static std::string formatHex(int value, bool prefix = false); + /// Formats an int value in hexadecimal notation. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + /// The value is treated as unsigned. + + static std::string formatHex(int value, int width, bool prefix = false); + /// Formats a int value in hexadecimal notation, + /// right justified and zero-padded in + /// a field having at least the specified width. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + /// The value is treated as unsigned. + + static std::string format(unsigned value); + /// Formats an unsigned int value in decimal notation. + + static std::string format(unsigned value, int width); + /// Formats an unsigned long int in decimal notation, + /// right justified in a field having at least the + /// specified width. + + static std::string format0(unsigned int value, int width); + /// Formats an unsigned int value in decimal notation, + /// right justified and zero-padded in a field having at + /// least the specified width. + + static std::string formatHex(unsigned value, bool prefix = false); + /// Formats an unsigned int value in hexadecimal notation. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + + static std::string formatHex(unsigned value, int width, bool prefix = false); + /// Formats a int value in hexadecimal notation, + /// right justified and zero-padded in + /// a field having at least the specified width. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + + static std::string format(long value); + /// Formats a long value in decimal notation. + + static std::string format(long value, int width); + /// Formats a long value in decimal notation, + /// right justified in a field having at least the + /// specified width. + + static std::string format0(long value, int width); + /// Formats a long value in decimal notation, + /// right justified and zero-padded in a field + /// having at least the specified width. + + static std::string formatHex(long value, bool prefix = false); + /// Formats an unsigned long value in hexadecimal notation. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + /// The value is treated as unsigned. + + static std::string formatHex(long value, int width, bool prefix = false); + /// Formats an unsigned long value in hexadecimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + /// The value is treated as unsigned. + + static std::string format(unsigned long value); + /// Formats an unsigned long value in decimal notation. + + static std::string format(unsigned long value, int width); + /// Formats an unsigned long value in decimal notation, + /// right justified in a field having at least the specified + /// width. + + static std::string format0(unsigned long value, int width); + /// Formats an unsigned long value in decimal notation, + /// right justified and zero-padded + /// in a field having at least the specified width. + + static std::string formatHex(unsigned long value, bool prefix = false); + /// Formats an unsigned long value in hexadecimal notation. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + + static std::string formatHex(unsigned long value, int width, bool prefix = false); + /// Formats an unsigned long value in hexadecimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + +#ifdef POCO_HAVE_INT64 + +#ifdef POCO_LONG_IS_64_BIT + + static std::string format(long long value); + /// Formats a 64-bit integer value in decimal notation. + + static std::string format(long long value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static std::string format0(long long value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + + static std::string formatHex(long long value, bool prefix = false); + /// Formats a 64-bit integer value in hexadecimal notation. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + /// The value is treated as unsigned. + + static std::string formatHex(long long value, int width, bool prefix = false); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + /// The value is treated as unsigned. + /// If prefix is true, "0x" prefix is prepended to the resulting string. + + static std::string format(unsigned long long value); + /// Formats an unsigned 64-bit integer value in decimal notation. + + static std::string format(unsigned long long value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static std::string format0(unsigned long long value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + + static std::string formatHex(unsigned long long value, bool prefix = false); + /// Formats a 64-bit integer value in hexadecimal notation. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + + static std::string formatHex(unsigned long long value, int width, bool prefix = false); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. If prefix is true, "0x" prefix is + /// prepended to the resulting string. + +#else // ifndef POCO_LONG_IS_64_BIT + + static std::string format(Int64 value); + /// Formats a 64-bit integer value in decimal notation. + + static std::string format(Int64 value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static std::string format0(Int64 value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + + static std::string formatHex(Int64 value, bool prefix = false); + /// Formats a 64-bit integer value in hexadecimal notation. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + /// The value is treated as unsigned. + + static std::string formatHex(Int64 value, int width, bool prefix = false); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + /// The value is treated as unsigned. + /// If prefix is true, "0x" prefix is prepended to the resulting string. + + static std::string format(UInt64 value); + /// Formats an unsigned 64-bit integer value in decimal notation. + + static std::string format(UInt64 value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static std::string format0(UInt64 value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + + static std::string formatHex(UInt64 value, bool prefix = false); + /// Formats a 64-bit integer value in hexadecimal notation. + /// If prefix is true, "0x" prefix is prepended to the + /// resulting string. + + static std::string formatHex(UInt64 value, int width, bool prefix = false); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. If prefix is true, "0x" prefix is + /// prepended to the resulting string. + +#endif // ifdef POCO_LONG_IS_64_BIT + +#endif // ifdef POCO_HAVE_INT64 + + static std::string format(float value); + /// Formats a float value in decimal floating-point notation, + /// according to std::printf's %g format with a precision of 8 fractional digits. + + static std::string format(float value, int precision); + /// Formats a double value in decimal floating-point notation, + /// according to std::printf's %f format with the given precision. + + static std::string format(float value, int width, int precision); + /// Formats a double value in decimal floating-point notation, + /// right justified in a field of the specified width, + /// with the number of fractional digits given in precision. + + static std::string format(double value); + /// Formats a double value in decimal floating-point notation, + /// according to std::printf's %g format with a precision of 16 fractional digits. + + static std::string format(double value, int precision); + /// Formats a double value in decimal floating-point notation, + /// according to std::printf's %f format with the given precision. + + static std::string format(double value, int width, int precision); + /// Formats a double value in decimal floating-point notation, + /// right justified in a field of the specified width, + /// with the number of fractional digits given in precision. + + static std::string format(const void* ptr); + /// Formats a pointer in an eight (32-bit architectures) or + /// sixteen (64-bit architectures) characters wide + /// field in hexadecimal notation. + + static std::string format(bool value, BoolFormat format = FMT_TRUE_FALSE); + /// Formats a bool value in decimal/text notation, + /// according to format parameter. + + static void append(std::string& str, int value); + /// Formats an integer value in decimal notation. + + static void append(std::string& str, int value, int width); + /// Formats an integer value in decimal notation, + /// right justified in a field having at least + /// the specified width. + + static void append0(std::string& str, int value, int width); + /// Formats an integer value in decimal notation, + /// right justified and zero-padded in a field + /// having at least the specified width. + + static void appendHex(std::string& str, int value); + /// Formats an int value in hexadecimal notation. + /// The value is treated as unsigned. + + static void appendHex(std::string& str, int value, int width); + /// Formats a int value in hexadecimal notation, + /// right justified and zero-padded in + /// a field having at least the specified width. + /// The value is treated as unsigned. + + static void append(std::string& str, unsigned value); + /// Formats an unsigned int value in decimal notation. + + static void append(std::string& str, unsigned value, int width); + /// Formats an unsigned long int in decimal notation, + /// right justified in a field having at least the + /// specified width. + + static void append0(std::string& str, unsigned int value, int width); + /// Formats an unsigned int value in decimal notation, + /// right justified and zero-padded in a field having at + /// least the specified width. + + static void appendHex(std::string& str, unsigned value); + /// Formats an unsigned int value in hexadecimal notation. + + static void appendHex(std::string& str, unsigned value, int width); + /// Formats a int value in hexadecimal notation, + /// right justified and zero-padded in + /// a field having at least the specified width. + + static void append(std::string& str, long value); + /// Formats a long value in decimal notation. + + static void append(std::string& str, long value, int width); + /// Formats a long value in decimal notation, + /// right justified in a field having at least the + /// specified width. + + static void append0(std::string& str, long value, int width); + /// Formats a long value in decimal notation, + /// right justified and zero-padded in a field + /// having at least the specified width. + + static void appendHex(std::string& str, long value); + /// Formats an unsigned long value in hexadecimal notation. + /// The value is treated as unsigned. + + static void appendHex(std::string& str, long value, int width); + /// Formats an unsigned long value in hexadecimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + /// The value is treated as unsigned. + + static void append(std::string& str, unsigned long value); + /// Formats an unsigned long value in decimal notation. + + static void append(std::string& str, unsigned long value, int width); + /// Formats an unsigned long value in decimal notation, + /// right justified in a field having at least the specified + /// width. + + static void append0(std::string& str, unsigned long value, int width); + /// Formats an unsigned long value in decimal notation, + /// right justified and zero-padded + /// in a field having at least the specified width. + + static void appendHex(std::string& str, unsigned long value); + /// Formats an unsigned long value in hexadecimal notation. + + static void appendHex(std::string& str, unsigned long value, int width); + /// Formats an unsigned long value in hexadecimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + +#ifdef POCO_HAVE_INT64 + +#ifdef POCO_LONG_IS_64_BIT + + static void append(std::string& str, long long value); + /// Formats a 64-bit integer value in decimal notation. + + static void append(std::string& str, long long value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static void append0(std::string& str, long long value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + + static void appendHex(std::string& str, long long value); + /// Formats a 64-bit integer value in hexadecimal notation. + /// The value is treated as unsigned. + + static void appendHex(std::string& str, long long value, int width); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + /// The value is treated as unsigned. + + static void append(std::string& str, unsigned long long value); + /// Formats an unsigned 64-bit integer value in decimal notation. + + static void append(std::string& str, unsigned long long value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static void append0(std::string& str, unsigned long long value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + + static void appendHex(std::string& str, unsigned long long value); + /// Formats a 64-bit integer value in hexadecimal notation. + + static void appendHex(std::string& str, unsigned long long value, int width); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + +#else // ifndef POCO_LONG_IS_64_BIT + + static void append(std::string& str, Int64 value); + /// Formats a 64-bit integer value in decimal notation. + + static void append(std::string& str, Int64 value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static void append0(std::string& str, Int64 value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + + static void appendHex(std::string& str, Int64 value); + /// Formats a 64-bit integer value in hexadecimal notation. + /// The value is treated as unsigned. + + static void appendHex(std::string& str, Int64 value, int width); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + /// The value is treated as unsigned. + + static void append(std::string& str, UInt64 value); + /// Formats an unsigned 64-bit integer value in decimal notation. + + static void append(std::string& str, UInt64 value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static void append0(std::string& str, UInt64 value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + + static void appendHex(std::string& str, UInt64 value); + /// Formats a 64-bit integer value in hexadecimal notation. + + static void appendHex(std::string& str, UInt64 value, int width); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + +#endif // ifdef POCO_LONG_IS_64_BIT + +#endif // ifdef POCO_HAVE_INT64 + + static void append(std::string& str, float value); + /// Formats a float value in decimal floating-point notation, + /// according to std::printf's %g format with a precision of 8 fractional digits. + + static void append(std::string& str, float value, int precision); + /// Formats a double value in decimal floating-point notation, + /// according to std::printf's %f format with the given precision. + + static void append(std::string& str, float value, int width, int precision); + /// Formats a double value in decimal floating-point notation, + /// right justified in a field of the specified width, + /// with the number of fractional digits given in precision. + + static void append(std::string& str, double value); + /// Formats a double value in decimal floating-point notation, + /// according to std::printf's %g format with a precision of 16 fractional digits. + + static void append(std::string& str, double value, int precision); + /// Formats a double value in decimal floating-point notation, + /// according to std::printf's %f format with the given precision. + + static void append(std::string& str, double value, int width, int precision); + /// Formats a double value in decimal floating-point notation, + /// right justified in a field of the specified width, + /// with the number of fractional digits given in precision. + + static void append(std::string& str, const void* ptr); + /// Formats a pointer in an eight (32-bit architectures) or + /// sixteen (64-bit architectures) characters wide + /// field in hexadecimal notation. + +private: +}; + + +// +// inlines +// + +inline std::string NumberFormatter::format(int value) +{ + std::string result; + intToStr(value, 10, result); + return result; +} + + +inline std::string NumberFormatter::format(int value, int width) +{ + std::string result; + intToStr(value, 10, result, false, width, ' '); + return result; +} + + +inline std::string NumberFormatter::format0(int value, int width) +{ + std::string result; + intToStr(value, 10, result, false, width, '0'); + return result; +} + + +inline std::string NumberFormatter::formatHex(int value, bool prefix) +{ + std::string result; + uIntToStr(static_cast<unsigned int>(value), 0x10, result, prefix); + return result; +} + + +inline std::string NumberFormatter::formatHex(int value, int width, bool prefix) +{ + std::string result; + uIntToStr(static_cast<unsigned int>(value), 0x10, result, prefix, width, '0'); + return result; +} + + +inline std::string NumberFormatter::format(unsigned value) +{ + std::string result; + uIntToStr(value, 10, result); + return result; +} + + +inline std::string NumberFormatter::format(unsigned value, int width) +{ + std::string result; + uIntToStr(value, 10, result, false, width, ' '); + return result; +} + + +inline std::string NumberFormatter::format0(unsigned int value, int width) +{ + std::string result; + uIntToStr(value, 10, result, false, width, '0'); + return result; +} + + +inline std::string NumberFormatter::formatHex(unsigned value, bool prefix) +{ + std::string result; + uIntToStr(value, 0x10, result, prefix); + return result; +} + + +inline std::string NumberFormatter::formatHex(unsigned value, int width, bool prefix) +{ + std::string result; + uIntToStr(value, 0x10, result, prefix, width, '0'); + return result; +} + + +inline std::string NumberFormatter::format(long value) +{ + std::string result; + intToStr(value, 10, result); + return result; +} + + +inline std::string NumberFormatter::format(long value, int width) +{ + std::string result; + intToStr(value, 10, result, false, width, ' '); + return result; +} + + +inline std::string NumberFormatter::format0(long value, int width) +{ + std::string result; + intToStr(value, 10, result, false, width, '0'); + return result; +} + + +inline std::string NumberFormatter::formatHex(long value, bool prefix) +{ + std::string result; + uIntToStr(static_cast<unsigned long>(value), 0x10, result, prefix); + return result; +} + + +inline std::string NumberFormatter::formatHex(long value, int width, bool prefix) +{ + std::string result; + uIntToStr(static_cast<unsigned long>(value), 0x10, result, prefix, width, '0'); + return result; +} + + +inline std::string NumberFormatter::format(unsigned long value) +{ + std::string result; + uIntToStr(value, 10, result); + return result; +} + + +inline std::string NumberFormatter::format(unsigned long value, int width) +{ + std::string result; + uIntToStr(value, 10, result, false, width, ' '); + return result; +} + + +inline std::string NumberFormatter::format0(unsigned long value, int width) +{ + std::string result; + uIntToStr(value, 10, result, false, width, '0'); + return result; +} + + +inline std::string NumberFormatter::formatHex(unsigned long value, bool prefix) +{ + std::string result; + uIntToStr(value, 0x10, result, prefix); + return result; +} + + +inline std::string NumberFormatter::formatHex(unsigned long value, int width, bool prefix) +{ + std::string result; + uIntToStr(value, 0x10, result, prefix, width, '0'); + return result; +} + + +#ifdef POCO_HAVE_INT64 + +#ifdef POCO_LONG_IS_64_BIT + + +inline std::string NumberFormatter::format(long long value) +{ + std::string result; + intToStr(value, 10, result); + return result; +} + + +inline std::string NumberFormatter::format(long long value, int width) +{ + std::string result; + intToStr(value, 10, result, false, width, ' '); + return result; +} + + +inline std::string NumberFormatter::format0(long long value, int width) +{ + std::string result; + intToStr(value, 10, result, false, width, '0'); + return result; +} + + +inline std::string NumberFormatter::formatHex(long long value, bool prefix) +{ + std::string result; + uIntToStr(static_cast<unsigned long long>(value), 0x10, result, prefix); + return result; +} + + +inline std::string NumberFormatter::formatHex(long long value, int width, bool prefix) +{ + std::string result; + uIntToStr(static_cast<unsigned long long>(value), 0x10, result, prefix, width, '0'); + return result; +} + + +inline std::string NumberFormatter::format(unsigned long long value) +{ + std::string result; + uIntToStr(value, 10, result); + return result; +} + + +inline std::string NumberFormatter::format(unsigned long long value, int width) +{ + std::string result; + uIntToStr(value, 10, result, false, width, ' '); + return result; +} + + +inline std::string NumberFormatter::format0(unsigned long long value, int width) +{ + std::string result; + uIntToStr(value, 10, result, false, width, '0'); + return result; +} + + +inline std::string NumberFormatter::formatHex(unsigned long long value, bool prefix) +{ + std::string result; + uIntToStr(value, 0x10, result, prefix); + return result; +} + + +inline std::string NumberFormatter::formatHex(unsigned long long value, int width, bool prefix) +{ + std::string result; + uIntToStr(value, 0x10, result, prefix, width, '0'); + return result; +} + + +#else // ifndef POCO_LONG_IS_64_BIT + + +inline std::string NumberFormatter::format(Int64 value) +{ + std::string result; + intToStr(value, 10, result); + return result; +} + + +inline std::string NumberFormatter::format(Int64 value, int width) +{ + std::string result; + intToStr(value, 10, result, false, width, ' '); + return result; +} + + +inline std::string NumberFormatter::format0(Int64 value, int width) +{ + std::string result; + intToStr(value, 10, result, false, width, '0'); + return result; +} + + +inline std::string NumberFormatter::formatHex(Int64 value, bool prefix) +{ + std::string result; + uIntToStr(static_cast<UInt64>(value), 0x10, result, prefix); + return result; +} + + +inline std::string NumberFormatter::formatHex(Int64 value, int width, bool prefix) +{ + std::string result; + uIntToStr(static_cast<UInt64>(value), 0x10, result, prefix, width, '0'); + return result; +} + + +inline std::string NumberFormatter::format(UInt64 value) +{ + std::string result; + uIntToStr(value, 10, result); + return result; +} + + +inline std::string NumberFormatter::format(UInt64 value, int width) +{ + std::string result; + uIntToStr(value, 10, result, false, width, ' '); + return result; +} + + +inline std::string NumberFormatter::format0(UInt64 value, int width) +{ + std::string result; + uIntToStr(value, 10, result, false, width, '0'); + return result; +} + + +inline std::string NumberFormatter::formatHex(UInt64 value, bool prefix) +{ + std::string result; + uIntToStr(value, 0x10, result, prefix); + return result; +} + + +inline std::string NumberFormatter::formatHex(UInt64 value, int width, bool prefix) +{ + std::string result; + uIntToStr(value, 0x10, result, prefix, width, '0'); + return result; +} + + +#endif // ifdef POCO_LONG_IS_64_BIT + +#endif // ifdef POCO_HAVE_INT64 + + +inline std::string NumberFormatter::format(float value) +{ + char buffer[POCO_MAX_FLT_STRING_LEN]; + floatToStr(buffer, POCO_MAX_FLT_STRING_LEN, value); + return std::string(buffer); +} + + +inline std::string NumberFormatter::format(float value, int precision) +{ + char buffer[POCO_MAX_FLT_STRING_LEN]; + floatToFixedStr(buffer, POCO_MAX_FLT_STRING_LEN, value, precision); + return std::string(buffer); +} + + +inline std::string NumberFormatter::format(float value, int width, int precision) +{ + std::string result; + floatToFixedStr(result, value, precision, width); + return result; +} + + +inline std::string NumberFormatter::format(double value) +{ + char buffer[POCO_MAX_FLT_STRING_LEN]; + doubleToStr(buffer, POCO_MAX_FLT_STRING_LEN, value); + return std::string(buffer); +} + + +inline std::string NumberFormatter::format(double value, int precision) +{ + char buffer[POCO_MAX_FLT_STRING_LEN]; + doubleToFixedStr(buffer, POCO_MAX_FLT_STRING_LEN, value, precision); + return std::string(buffer); +} + + +inline std::string NumberFormatter::format(double value, int width, int precision) +{ + std::string result; + doubleToFixedStr(result, value, precision, width); + return result; +} + + +inline std::string NumberFormatter::format(const void* ptr) +{ + std::string result; + append(result, ptr); + return result; +} + + +} // namespace Poco + + +#endif // Foundation_NumberFormatter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NumberParser.h b/contrib/libs/poco/Foundation/include/Poco/NumberParser.h new file mode 100644 index 0000000000..c58ed4f359 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NumberParser.h @@ -0,0 +1,156 @@ +// +// NumberParser.h +// +// Library: Foundation +// Package: Core +// Module: NumberParser +// +// Definition of the NumberParser class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NumberParser_INCLUDED +#define Foundation_NumberParser_INCLUDED + + +#include "Poco/Foundation.h" +#include <string> +#undef min +#undef max +#include <limits> + + +namespace Poco { + + +class Foundation_API NumberParser + /// The NumberParser class provides static methods + /// for parsing numbers out of strings. + /// + /// Note that leading or trailing whitespace is not allowed + /// in the string. Poco::trim() or Poco::trimInPlace() + /// can be used to remove leading or trailing whitespace. +{ +public: + static const unsigned short NUM_BASE_OCT = 010; + static const unsigned short NUM_BASE_DEC = 10; + static const unsigned short NUM_BASE_HEX = 0x10; + + static int parse(const std::string& s, char thousandSeparator = ','); + /// Parses an integer value in decimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in decimal notation. + + static bool tryParse(const std::string& s, int& value, char thousandSeparator = ','); + /// Parses an integer value in decimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + /// If parsing was not successful, value is undefined. + + static unsigned parseUnsigned(const std::string& s, char thousandSeparator = ','); + /// Parses an unsigned integer value in decimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in decimal notation. + + static bool tryParseUnsigned(const std::string& s, unsigned& value, char thousandSeparator = ','); + /// Parses an unsigned integer value in decimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + /// If parsing was not successful, value is undefined. + + static unsigned parseHex(const std::string& s); + /// Parses an integer value in hexadecimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in + /// hexadecimal notation. + + static bool tryParseHex(const std::string& s, unsigned& value); + /// Parses an unsigned integer value in hexadecimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + /// If parsing was not successful, value is undefined. + + static unsigned parseOct(const std::string& s); + /// Parses an integer value in octal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in + /// hexadecimal notation. + + static bool tryParseOct(const std::string& s, unsigned& value); + /// Parses an unsigned integer value in octal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + /// If parsing was not successful, value is undefined. + +#if defined(POCO_HAVE_INT64) + + static Int64 parse64(const std::string& s, char thousandSeparator = ','); + /// Parses a 64-bit integer value in decimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in decimal notation. + + static bool tryParse64(const std::string& s, Int64& value, char thousandSeparator = ','); + /// Parses a 64-bit integer value in decimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + /// If parsing was not successful, value is undefined. + + static UInt64 parseUnsigned64(const std::string& s, char thousandSeparator = ','); + /// Parses an unsigned 64-bit integer value in decimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in decimal notation. + + static bool tryParseUnsigned64(const std::string& s, UInt64& value, char thousandSeparator = ','); + /// Parses an unsigned 64-bit integer value in decimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + /// If parsing was not successful, value is undefined. + + static UInt64 parseHex64(const std::string& s); + /// Parses a 64 bit-integer value in hexadecimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in hexadecimal notation. + + static bool tryParseHex64(const std::string& s, UInt64& value); + /// Parses an unsigned 64-bit integer value in hexadecimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + /// If parsing was not successful, value is undefined. + + static UInt64 parseOct64(const std::string& s); + /// Parses a 64 bit-integer value in octal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in hexadecimal notation. + + static bool tryParseOct64(const std::string& s, UInt64& value); + /// Parses an unsigned 64-bit integer value in octal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + /// If parsing was not successful, value is undefined. + +#endif // defined(POCO_HAVE_INT64) + + static double parseFloat(const std::string& s, char decimalSeparator = '.', char thousandSeparator = ','); + /// Parses a double value in decimal floating point notation + /// from the given string. + /// Throws a SyntaxException if the string does not hold a floating-point + /// number in decimal notation. + + static bool tryParseFloat(const std::string& s, double& value, char decimalSeparator = '.', char thousandSeparator = ','); + /// Parses a double value in decimal floating point notation + /// from the given string. + /// Returns true if a valid floating point number has been found, + /// false otherwise. + /// If parsing was not successful, value is undefined. + + static bool parseBool(const std::string& s); + /// Parses a bool value in decimal or string notation + /// from the given string. + /// Valid forms are: "0", "1", "true", "on", false", "yes", "no", "off". + /// String forms are NOT case sensitive. + /// Throws a SyntaxException if the string does not hold a valid bool number + + static bool tryParseBool(const std::string& s, bool& value); + /// Parses a bool value in decimal or string notation + /// from the given string. + /// Valid forms are: "0", "1", "true", "on", false", "yes", "no", "off". + /// String forms are NOT case sensitive. + /// Returns true if a valid bool number has been found, + /// false otherwise. + /// If parsing was not successful, value is undefined. +}; + + +} // namespace Poco + + +#endif // Foundation_NumberParser_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/NumericString.h b/contrib/libs/poco/Foundation/include/Poco/NumericString.h new file mode 100644 index 0000000000..5600432d29 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/NumericString.h @@ -0,0 +1,560 @@ +// +// NumericString.h +// +// Library: Foundation +// Package: Core +// Module: NumericString +// +// Numeric string utility functions. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_NumericString_INCLUDED +#define Foundation_NumericString_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Buffer.h" +#include "Poco/FPEnvironment.h" +#ifdef min + #undef min +#endif +#ifdef max + #undef max +#endif +#include <limits> +#include <cmath> +#include <cctype> +#if !defined(POCO_NO_LOCALE) + #include <locale> +#endif + + +// binary numbers are supported, thus 64 (bits) + 1 (string terminating zero) +#define POCO_MAX_INT_STRING_LEN 65 +// value from strtod.cc (double_conversion::kMaxSignificantDecimalDigits) +#define POCO_MAX_FLT_STRING_LEN 780 + +#define POCO_FLT_INF "inf" +#define POCO_FLT_NAN "nan" +#define POCO_FLT_EXP 'e' + + +namespace Poco { + + +inline char decimalSeparator() + /// Returns decimal separator from global locale or + /// default '.' for platforms where locale is unavailable. +{ +#if !defined(POCO_NO_LOCALE) + return std::use_facet<std::numpunct<char> >(std::locale()).decimal_point(); +#else + return '.'; +#endif +} + + +inline char thousandSeparator() + /// Returns thousand separator from global locale or + /// default ',' for platforms where locale is unavailable. +{ +#if !defined(POCO_NO_LOCALE) + return std::use_facet<std::numpunct<char> >(std::locale()).thousands_sep(); +#else + return ','; +#endif +} + + +// +// String to Number Conversions +// + +template <typename I> +bool strToInt(const char* pStr, I& result, short base, char thSep = ',') + /// Converts zero-terminated character array to integer number; + /// Thousand separators are recognized for base10 and current locale; + /// it is silently skipped but not verified for correct positioning. + /// Function returns true if successful. If parsing was unsuccessful, + /// the return value is false with the result value undetermined. +{ + if (!pStr) return false; + while (std::isspace(*pStr)) ++pStr; + if (*pStr == '\0') return false; + short sign = 1; + if ((base == 10) && (*pStr == '-')) + { + // Unsigned types can't be negative so abort parsing + if (std::numeric_limits<I>::min() >= 0) return false; + sign = -1; + ++pStr; + } + else if (*pStr == '+') ++pStr; + + // parser states: + const char STATE_SIGNIFICANT_DIGITS = 1; + char state = 0; + + result = 0; + I limitCheck = std::numeric_limits<I>::max() / base; + for (; *pStr != '\0'; ++pStr) + { + switch (*pStr) + { + case '0': + if (state < STATE_SIGNIFICANT_DIGITS) break; + + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': + if (state < STATE_SIGNIFICANT_DIGITS) state = STATE_SIGNIFICANT_DIGITS; + if (result > limitCheck) return false; + result = result * base + (*pStr - '0'); + + break; + + case '8': case '9': + if ((base == 10) || (base == 0x10)) + { + if (state < STATE_SIGNIFICANT_DIGITS) state = STATE_SIGNIFICANT_DIGITS; + if (result > limitCheck) return false; + result = result * base + (*pStr - '0'); + } + else return false; + + break; + + case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': + if (base != 0x10) return false; + if (state < STATE_SIGNIFICANT_DIGITS) state = STATE_SIGNIFICANT_DIGITS; + if (result > limitCheck) return false; + result = result * base + (10 + *pStr - 'a'); + + break; + + case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': + if (base != 0x10) return false; + if (state < STATE_SIGNIFICANT_DIGITS) state = STATE_SIGNIFICANT_DIGITS; + if (result > limitCheck) return false; + result = result * base + (10 + *pStr - 'A'); + + break; + + case '.': + if ((base == 10) && (thSep == '.')) break; + else return false; + + case ',': + if ((base == 10) && (thSep == ',')) break; + else return false; + + case ' ': + if ((base == 10) && (thSep == ' ')) break; + // fallthrough + + default: + return false; + } + } + + if ((sign < 0) && (base == 10)) result *= sign; + + return true; +} + + +template <typename I> +bool strToInt(const std::string& str, I& result, short base, char thSep = ',') + /// Converts string to integer number; + /// This is a wrapper function, for details see see the + /// bool strToInt(const char*, I&, short, char) implementation. +{ + return strToInt(str.c_str(), result, base, thSep); +} + + +// +// Number to String Conversions +// + +namespace Impl { + + class Ptr + /// Utility char pointer wrapper class. + /// Class ensures increment/decrement remain within boundaries. + { + public: + Ptr(char* ptr, std::size_t offset): _beg(ptr), _cur(ptr), _end(ptr + offset) + { + } + + char*& operator ++ () // prefix + { + checkBounds(_cur + 1); + return ++_cur; + } + + char* operator ++ (int) // postfix + { + checkBounds(_cur + 1); + char* tmp = _cur++; + return tmp; + } + + char*& operator -- () // prefix + { + checkBounds(_cur - 1); + return --_cur; + } + + char* operator -- (int) // postfix + { + checkBounds(_cur - 1); + char* tmp = _cur--; + return tmp; + } + + char*& operator += (int incr) + { + checkBounds(_cur + incr); + return _cur += incr; + } + + char*& operator -= (int decr) + { + checkBounds(_cur - decr); + return _cur -= decr; + } + + operator char* () const + { + return _cur; + } + + std::size_t span() const + { + return _end - _beg; + } + + private: + void checkBounds(char* ptr) + { + if (ptr > _end) throw RangeException(); + } + + const char* _beg; + char* _cur; + const char* _end; +}; + +} // namespace Impl + + +template <typename T> +bool intToStr(T value, + unsigned short base, + char* result, + std::size_t& size, + bool prefix = false, + int width = -1, + char fill = ' ', + char thSep = 0) + /// Converts integer to string. Numeric bases from binary to hexadecimal are supported. + /// If width is non-zero, it pads the return value with fill character to the specified width. + /// When padding is zero character ('0'), it is prepended to the number itself; all other + /// paddings are prepended to the formatted result with minus sign or base prefix included + /// If prefix is true and base is octal or hexadecimal, respective prefix ('0' for octal, + /// "0x" for hexadecimal) is prepended. For all other bases, prefix argument is ignored. + /// Formatted string has at least [width] total length. +{ + if (base < 2 || base > 0x10) + { + *result = '\0'; + return false; + } + + Impl::Ptr ptr(result, size); + int thCount = 0; + T tmpVal; + do + { + tmpVal = value; + value /= base; + *ptr++ = "FEDCBA9876543210123456789ABCDEF"[15 + (tmpVal - value * base)]; + if (thSep && (base == 10) && (++thCount == 3)) + { + *ptr++ = thSep; + thCount = 0; + } + } while (value); + + if ('0' == fill) + { + if (tmpVal < 0) --width; + if (prefix && base == 010) --width; + if (prefix && base == 0x10) width -= 2; + while ((ptr - result) < width) *ptr++ = fill; + } + + if (prefix && base == 010) *ptr++ = '0'; + else if (prefix && base == 0x10) + { + *ptr++ = 'x'; + *ptr++ = '0'; + } + + if (tmpVal < 0) *ptr++ = '-'; + + if ('0' != fill) + { + while ((ptr - result) < width) *ptr++ = fill; + } + + size = ptr - result; + poco_assert_dbg (size <= ptr.span()); + poco_assert_dbg ((-1 == width) || (size >= std::size_t(width))); + *ptr-- = '\0'; + + char* ptrr = result; + char tmp; + while(ptrr < ptr) + { + tmp = *ptr; + *ptr-- = *ptrr; + *ptrr++ = tmp; + } + + return true; +} + + +template <typename T> +bool uIntToStr(T value, + unsigned short base, + char* result, + std::size_t& size, + bool prefix = false, + int width = -1, + char fill = ' ', + char thSep = 0) + /// Converts unsigned integer to string. Numeric bases from binary to hexadecimal are supported. + /// If width is non-zero, it pads the return value with fill character to the specified width. + /// When padding is zero character ('0'), it is prepended to the number itself; all other + /// paddings are prepended to the formatted result with minus sign or base prefix included + /// If prefix is true and base is octal or hexadecimal, respective prefix ('0' for octal, + /// "0x" for hexadecimal) is prepended. For all other bases, prefix argument is ignored. + /// Formatted string has at least [width] total length. +{ + if (base < 2 || base > 0x10) + { + *result = '\0'; + return false; + } + + Impl::Ptr ptr(result, size); + int thCount = 0; + T tmpVal; + do + { + tmpVal = value; + value /= base; + *ptr++ = "FEDCBA9876543210123456789ABCDEF"[15 + (tmpVal - value * base)]; + if (thSep && (base == 10) && (++thCount == 3)) + { + *ptr++ = thSep; + thCount = 0; + } + } while (value); + + if ('0' == fill) + { + if (prefix && base == 010) --width; + if (prefix && base == 0x10) width -= 2; + while ((ptr - result) < width) *ptr++ = fill; + } + + if (prefix && base == 010) *ptr++ = '0'; + else if (prefix && base == 0x10) + { + *ptr++ = 'x'; + *ptr++ = '0'; + } + + if ('0' != fill) + { + while ((ptr - result) < width) *ptr++ = fill; + } + + size = ptr - result; + poco_assert_dbg (size <= ptr.span()); + poco_assert_dbg ((-1 == width) || (size >= std::size_t(width))); + *ptr-- = '\0'; + + char* ptrr = result; + char tmp; + while(ptrr < ptr) + { + tmp = *ptr; + *ptr-- = *ptrr; + *ptrr++ = tmp; + } + + return true; +} + + +template <typename T> +bool intToStr (T number, unsigned short base, std::string& result, bool prefix = false, int width = -1, char fill = ' ', char thSep = 0) + /// Converts integer to string; This is a wrapper function, for details see see the + /// bool intToStr(T, unsigned short, char*, int, int, char, char) implementation. +{ + char res[POCO_MAX_INT_STRING_LEN] = {0}; + std::size_t size = POCO_MAX_INT_STRING_LEN; + bool ret = intToStr(number, base, res, size, prefix, width, fill, thSep); + result.assign(res, size); + return ret; +} + + +template <typename T> +bool uIntToStr (T number, unsigned short base, std::string& result, bool prefix = false, int width = -1, char fill = ' ', char thSep = 0) + /// Converts unsigned integer to string; This is a wrapper function, for details see see the + /// bool uIntToStr(T, unsigned short, char*, int, int, char, char) implementation. +{ + char res[POCO_MAX_INT_STRING_LEN] = {0}; + std::size_t size = POCO_MAX_INT_STRING_LEN; + bool ret = uIntToStr(number, base, res, size, prefix, width, fill, thSep); + result.assign(res, size); + return ret; +} + + +// +// Wrappers for double-conversion library (http://code.google.com/p/double-conversion/). +// +// Library is the implementation of the algorithm described in Florian Loitsch's paper: +// http://florian.loitsch.com/publications/dtoa-pldi2010.pdf +// + + +Foundation_API void floatToStr(char* buffer, + int bufferSize, + float value, + int lowDec = -std::numeric_limits<float>::digits10, + int highDec = std::numeric_limits<float>::digits10); + /// Converts a float value to string. Converted string must be shorter than bufferSize. + /// Conversion is done by computing the shortest string of digits that correctly represents + /// the input number. Depending on lowDec and highDec values, the function returns + /// decimal or exponential representation. + +Foundation_API void floatToFixedStr(char* buffer, + int bufferSize, + float value, + int precision); + /// Converts a float value to string. Converted string must be shorter than bufferSize. + /// Computes a decimal representation with a fixed number of digits after the + /// decimal point. + + +Foundation_API std::string& floatToStr(std::string& str, + float value, + int precision = -1, + int width = 0, + char thSep = 0, + char decSep = 0); + /// Converts a float value, assigns it to the supplied string and returns the reference. + /// This function calls floatToStr(char*, int, float, int, int) and formats the result according to + /// precision (total number of digits after the decimal point, -1 means ignore precision argument) + /// and width (total length of formatted string). + + +Foundation_API std::string& floatToFixedStr(std::string& str, + float value, + int precision, + int width = 0, + char thSep = 0, + char decSep = 0); + /// Converts a float value, assigns it to the supplied string and returns the reference. + /// This function calls floatToFixedStr(char*, int, float, int) and formats the result according to + /// precision (total number of digits after the decimal point) and width (total length of formatted string). + + +Foundation_API void doubleToStr(char* buffer, + int bufferSize, + double value, + int lowDec = -std::numeric_limits<double>::digits10, + int highDec = std::numeric_limits<double>::digits10); + /// Converts a double value to string. Converted string must be shorter than bufferSize. + /// Conversion is done by computing the shortest string of digits that correctly represents + /// the input number. Depending on lowDec and highDec values, the function returns + /// decimal or exponential representation. + + +Foundation_API void doubleToFixedStr(char* buffer, + int bufferSize, + double value, + int precision); + /// Converts a double value to string. Converted string must be shorter than bufferSize. + /// Computes a decimal representation with a fixed number of digits after the + /// decimal point. + + +Foundation_API std::string& doubleToStr(std::string& str, + double value, + int precision = -1, + int width = 0, + char thSep = 0, + char decSep = 0); + /// Converts a double value, assigns it to the supplied string and returns the reference. + /// This function calls doubleToStr(char*, int, double, int, int) and formats the result according to + /// precision (total number of digits after the decimal point, -1 means ignore precision argument) + /// and width (total length of formatted string). + + +Foundation_API std::string& doubleToFixedStr(std::string& str, + double value, + int precision = -1, + int width = 0, + char thSep = 0, + char decSep = 0); + /// Converts a double value, assigns it to the supplied string and returns the reference. + /// This function calls doubleToFixedStr(char*, int, double, int) and formats the result according to + /// precision (total number of digits after the decimal point) and width (total length of formatted string). + + +Foundation_API float strToFloat(const char* str); + /// Converts the string of characters into single-precision floating point number. + /// Function uses double_convesrion::DoubleToStringConverter to do the conversion. + + +Foundation_API bool strToFloat(const std::string&, float& result, char decSep = '.', char thSep = ','); + /// Converts the string of characters into single-precision floating point number. + /// The conversion result is assigned to the result parameter. + /// If decimal separator and/or thousand separator are different from defaults, they should be + /// supplied to ensure proper conversion. + /// + /// Returns true if successful, false otherwise. + + +Foundation_API double strToDouble(const char* str); + /// Converts the string of characters into double-precision floating point number. + + +Foundation_API bool strToDouble(const std::string& str, double& result, char decSep = '.', char thSep = ','); + /// Converts the string of characters into double-precision floating point number. + /// The conversion result is assigned to the result parameter. + /// If decimal separator and/or thousand separator are different from defaults, they should be + /// supplied to ensure proper conversion. + /// + /// Returns true if successful, false otherwise. + + +} // namespace Poco + + +#endif // Foundation_NumericString_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ObjectPool.h b/contrib/libs/poco/Foundation/include/Poco/ObjectPool.h new file mode 100644 index 0000000000..af3d7bab05 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ObjectPool.h @@ -0,0 +1,332 @@ +// +// ObjectPool.h +// +// Library: Foundation +// Package: Core +// Module: ObjectPool +// +// Definition of the ObjectPool template class and friends. +// +// Copyright (c) 2010-2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ObjectPool_INCLUDED +#define Foundation_ObjectPool_INCLUDED + + +#include "Poco/Poco.h" +#include "Poco/Mutex.h" +#include "Poco/Condition.h" +#include "Poco/AutoPtr.h" +#include "Poco/SharedPtr.h" +#include <vector> +#include <cctype> + + +namespace Poco { + + +template <class C, class P = C*> +class PoolableObjectFactory + /// A PoolableObjectFactory is responsible for creating and resetting + /// objects managed by an ObjectPool. + /// + /// Together with an ObjectPool, a PoolableObjectFactory is used as + /// a policy class to change the behavior of the ObjectPool when + /// creating new objects, returning used objects back to the pool + /// and destroying objects, when the pool itself is destroyed or + /// shrunk. +{ +public: + P createObject() + /// Create and return a new object. + { + return new C; + } + + bool validateObject(P pObject) + /// Checks whether the object is still valid + /// and can be reused. + /// + /// Returns true if the object is valid, + /// false otherwise. + /// + /// To maintain the integrity of the pool, this method + /// must not throw an exception. + { + return true; + } + + void activateObject(P pObject) + /// Called before an object is handed out by the pool. + /// Also called for newly created objects, before + /// they are given out for the first time. + { + } + + void deactivateObject(P pObject) + /// Called after an object has been given back to the + /// pool and the object is still valid (a prior call + /// to validateObject() returned true). + /// + /// To maintain the integrity of the pool, this method + /// must not throw an exception. + { + } + + void destroyObject(P pObject) + /// Destroy an object. + /// + /// To maintain the integrity of the pool, this method + /// must not throw an exception. + { + delete pObject; + } +}; + + +template <class C> +class PoolableObjectFactory <C, Poco::AutoPtr<C> > +{ +public: + Poco::AutoPtr<C> createObject() + { + return new C; + } + + bool validateObject(Poco::AutoPtr<C> pObject) + { + return true; + } + + void activateObject(Poco::AutoPtr<C> pObject) + { + } + + void deactivateObject(Poco::AutoPtr<C> pObject) + { + } + + void destroyObject(Poco::AutoPtr<C> pObject) + { + } +}; + + +template <class C> +class PoolableObjectFactory <C, Poco::SharedPtr<C> > +{ +public: + Poco::SharedPtr<C> createObject() + { + return new C; + } + + bool validateObject(Poco::SharedPtr<C> pObject) + { + return true; + } + + void activateObject(Poco::SharedPtr<C> pObject) + { + } + + void deactivateObject(Poco::SharedPtr<C> pObject) + { + } + + void destroyObject(Poco::SharedPtr<C> pObject) + { + } +}; + + +template <class C, class P = C*, class F = PoolableObjectFactory<C, P> > +class ObjectPool + /// An ObjectPool manages a pool of objects of a certain class. + /// + /// The number of objects managed by the pool can be restricted. + /// + /// When an object is requested from the pool: + /// - If an object is available from the pool, an object from the pool is + /// removed from the pool, activated (using the factory) and returned. + /// - Otherwise, if the peak capacity of the pool has not yet been reached, + /// a new object is created and activated, using the object factory, and returned. + /// - If the peak capacity has already been reached, null is returned after timeout. + /// + /// When an object is returned to the pool: + /// - If the object is valid (checked by calling validateObject() + /// from the object factory), the object is deactivated. If the + /// number of objects in the pool is below the capacity, + /// the object is added to the pool. Otherwise it is destroyed. + /// - If the object is not valid, it is destroyed immediately. +{ +public: + ObjectPool(std::size_t capacity, std::size_t peakCapacity): + /// Creates a new ObjectPool with the given capacity + /// and peak capacity. + /// + /// The PoolableObjectFactory must have a public default constructor. + _capacity(capacity), + _peakCapacity(peakCapacity), + _size(0) + { + poco_assert (capacity <= peakCapacity); + } + + ObjectPool(const F& factory, std::size_t capacity, std::size_t peakCapacity): + /// Creates a new ObjectPool with the given PoolableObjectFactory, + /// capacity and peak capacity. The PoolableObjectFactory must have + /// a public copy constructor. + _factory(factory), + _capacity(capacity), + _peakCapacity(peakCapacity), + _size(0) + { + poco_assert (capacity <= peakCapacity); + } + + ~ObjectPool() + /// Destroys the ObjectPool. + { + try + { + for (typename std::vector<P>::iterator it = _pool.begin(); it != _pool.end(); ++it) + { + _factory.destroyObject(*it); + } + } + catch (...) + { + poco_unexpected(); + } + } + + P borrowObject(long timeoutMilliseconds = 0) + /// Obtains an object from the pool, or creates a new object if + /// possible. + /// + /// Returns null if no object is available after timeout. + /// + /// If activating the object fails, the object is destroyed and + /// the exception is passed on to the caller. + { + Poco::FastMutex::ScopedLock lock(_mutex); + + if (!_pool.empty()) + { + P pObject = _pool.back(); + _pool.pop_back(); + return activateObject(pObject); + } + + if (_size >= _peakCapacity) + { + if (timeoutMilliseconds == 0) + { + return 0; + } + while (_size >= _peakCapacity) + { + if ( !_availableCondition.tryWait(_mutex, timeoutMilliseconds)) + { + // timeout + return 0; + } + } + } + + // _size < _peakCapacity + P pObject = _factory.createObject(); + activateObject(pObject); + _size++; + return pObject; + } + + void returnObject(P pObject) + /// Returns an object to the pool. + { + Poco::FastMutex::ScopedLock lock(_mutex); + + if (_factory.validateObject(pObject)) + { + _factory.deactivateObject(pObject); + if (_pool.size() < _capacity) + { + try + { + _pool.push_back(pObject); + return; + } + catch (...) + { + } + } + } + _factory.destroyObject(pObject); + _size--; + _availableCondition.signal(); + } + + std::size_t capacity() const + { + return _capacity; + } + + std::size_t peakCapacity() const + { + return _peakCapacity; + } + + std::size_t size() const + { + Poco::FastMutex::ScopedLock lock(_mutex); + + return _size; + } + + std::size_t available() const + { + Poco::FastMutex::ScopedLock lock(_mutex); + + return _pool.size() + _peakCapacity - _size; + } + +protected: + P activateObject(P pObject) + { + try + { + _factory.activateObject(pObject); + } + catch (...) + { + _factory.destroyObject(pObject); + throw; + } + return pObject; + } + +private: + ObjectPool(); + ObjectPool(const ObjectPool&); + ObjectPool& operator = (const ObjectPool&); + + F _factory; + std::size_t _capacity; + std::size_t _peakCapacity; + std::size_t _size; + std::vector<P> _pool; + mutable Poco::FastMutex _mutex; + Poco::Condition _availableCondition; +}; + + +} // namespace Poco + + +#endif // Foundation_ObjectPool_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Observer.h b/contrib/libs/poco/Foundation/include/Poco/Observer.h new file mode 100644 index 0000000000..98d94e0621 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Observer.h @@ -0,0 +1,124 @@ +// +// Observer.h +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Definition of the Observer class template. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Observer_INCLUDED +#define Foundation_Observer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractObserver.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class C, class N> +class Observer: public AbstractObserver + /// This template class implements an adapter that sits between + /// a NotificationCenter and an object receiving notifications + /// from it. It is quite similar in concept to the + /// RunnableAdapter, but provides some NotificationCenter + /// specific additional methods. + /// See the NotificationCenter class for information on how + /// to use this template class. + /// + /// Instead of the Observer class template, you might want to + /// use the NObserver class template, which uses an AutoPtr to + /// pass the Notification to the callback function, thus freeing + /// you from memory management issues. +{ +public: + typedef void (C::*Callback)(N*); + + Observer(C& object, Callback method): + _pObject(&object), + _method(method) + { + } + + Observer(const Observer& observer): + AbstractObserver(observer), + _pObject(observer._pObject), + _method(observer._method) + { + } + + ~Observer() + { + } + + Observer& operator = (const Observer& observer) + { + if (&observer != this) + { + _pObject = observer._pObject; + _method = observer._method; + } + return *this; + } + + void notify(Notification* pNf) const + { + Poco::Mutex::ScopedLock lock(_mutex); + + if (_pObject) + { + N* pCastNf = dynamic_cast<N*>(pNf); + if (pCastNf) + { + pCastNf->duplicate(); + (_pObject->*_method)(pCastNf); + } + } + } + + bool equals(const AbstractObserver& abstractObserver) const + { + const Observer* pObs = dynamic_cast<const Observer*>(&abstractObserver); + return pObs && pObs->_pObject == _pObject && pObs->_method == _method; + } + + bool accepts(Notification* pNf) const + { + return dynamic_cast<N*>(pNf) != 0; + } + + AbstractObserver* clone() const + { + return new Observer(*this); + } + + void disable() + { + Poco::Mutex::ScopedLock lock(_mutex); + + _pObject = 0; + } + +private: + Observer(); + + C* _pObject; + Callback _method; + mutable Poco::Mutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_Observer_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Optional.h b/contrib/libs/poco/Foundation/include/Poco/Optional.h new file mode 100644 index 0000000000..54593b16cc --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Optional.h @@ -0,0 +1,161 @@ +// +// Optional.h +// +// Library: Foundation +// Package: Core +// Module: Optional +// +// Definition of the Optional class template. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Optional_INCLUDED +#define Foundation_Optional_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <algorithm> + + +namespace Poco { + + +template <typename C> +class Optional + /// Optional is a simple wrapper class for value types + /// that allows to introduce a specified/unspecified state + /// to value objects. + /// + /// An Optional can be default constructed. In this case, + /// the Optional will have a Null value and isSpecified() will + /// return false. Calling value()(without default value) on + /// a Null object will throw a NullValueException. + /// + /// An Optional can also be constructed from a value. + /// It is possible to assign a value to an Optional, and + /// to reset an Optional to contain a Null value by calling + /// clear(). + /// + /// For use with Optional, the value type should support + /// default construction. + /// + /// Note that the Optional class is basically the same as + /// Nullable. However, serializers may treat Nullable + /// and Optional differently. An example is XML serialization based + /// on XML Schema, where Optional would be used for an element with + /// minOccurs == 0, whereas Nullable would be used on an element with + /// nillable == true. +{ +public: + Optional(): + /// Creates an empty Optional. + _value(), + _isSpecified(false) + { + } + + Optional(const C& value): + /// Creates a Optional with the given value. + _value(value), + _isSpecified(true) + { + } + + Optional(const Optional& other): + /// Creates a Optional by copying another one. + _value(other._value), + _isSpecified(other._isSpecified) + { + } + + ~Optional() + /// Destroys the Optional. + { + } + + Optional& assign(const C& value) + /// Assigns a value to the Optional. + { + _value = value; + _isSpecified = true; + return *this; + } + + Optional& assign(const Optional& other) + /// Assigns another Optional. + { + Optional tmp(other); + swap(tmp); + return *this; + } + + Optional& operator = (const C& value) + { + return assign(value); + } + + Optional& operator = (const Optional& other) + { + return assign(other); + } + + void swap(Optional& other) + { + std::swap(_value, other._value); + std::swap(_isSpecified, other._isSpecified); + } + + const C& value() const + /// Returns the Optional's value. + /// + /// Throws a Poco::NullValueException if the value has not been specified. + { + if (_isSpecified) + return _value; + else + throw Poco::NullValueException(); + } + + const C& value(const C& deflt) const + /// Returns the Optional's value, or the + /// given default value if the Optional's + /// value has not been specified. + { + return _isSpecified ? _value : deflt; + } + + bool isSpecified() const + /// Returns true iff the Optional's value has been specified. + { + return _isSpecified; + } + + void clear() + /// Clears the Optional. + { + _isSpecified = false; + } + +private: + C _value; + bool _isSpecified; +}; + + +template <typename C> +inline void swap(Optional<C>& n1, Optional<C>& n2) +{ + n1.swap(n2); +} + + +} // namespace Poco + + +#endif // Foundation_Optional_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PBKDF2Engine.h b/contrib/libs/poco/Foundation/include/Poco/PBKDF2Engine.h new file mode 100644 index 0000000000..357d482afe --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PBKDF2Engine.h @@ -0,0 +1,149 @@ +// +// PBKDF2Engine.h +// +// Library: Foundation +// Package: Crypt +// Module: PBKDF2Engine +// +// Definition of the PBKDF2Engine class. +// +// Copyright (c) 2014, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PBKDF2Engine_INCLUDED +#define Foundation_PBKDF2Engine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" +#include "Poco/ByteOrder.h" +#include <algorithm> + + +namespace Poco { + + +template <class PRF> +class PBKDF2Engine: public DigestEngine + /// This class implementes the Password-Based Key Derivation Function 2, + /// as specified in RFC 2898. The underlying DigestEngine (HMACEngine, etc.), + /// which must accept the passphrase as constructor argument (std::string), + /// must be given as template argument. + /// + /// PBKDF2 (Password-Based Key Derivation Function 2) is a key derivation function + /// that is part of RSA Laboratories' Public-Key Cryptography Standards (PKCS) series, + /// specifically PKCS #5 v2.0, also published as Internet Engineering Task Force's + /// RFC 2898. It replaces an earlier standard, PBKDF1, which could only produce + /// derived keys up to 160 bits long. + /// + /// PBKDF2 applies a pseudorandom function, such as a cryptographic hash, cipher, or + /// HMAC to the input password or passphrase along with a salt value and repeats the + /// process many times to produce a derived key, which can then be used as a + /// cryptographic key in subsequent operations. The added computational work makes + /// password cracking much more difficult, and is known as key stretching. + /// When the standard was written in 2000, the recommended minimum number of + /// iterations was 1000, but the parameter is intended to be increased over time as + /// CPU speeds increase. Having a salt added to the password reduces the ability to + /// use precomputed hashes (rainbow tables) for attacks, and means that multiple + /// passwords have to be tested individually, not all at once. The standard + /// recommends a salt length of at least 64 bits. [Wikipedia] + /// + /// The PBKDF2 algorithm is implemented as a DigestEngine. The passphrase is specified + /// by calling update(). + /// + /// Example (WPA2): + /// PBKDF2Engine<HMACEngine<SHA1Engine> > pbkdf2(ssid, 4096, 256); + /// pbkdf2.update(passphrase); + /// DigestEngine::Digest d = pbkdf2.digest(); +{ +public: + enum + { + PRF_DIGEST_SIZE = PRF::DIGEST_SIZE + }; + + PBKDF2Engine(const std::string& salt, unsigned c = 4096, Poco::UInt32 dkLen = PRF_DIGEST_SIZE): + _s(salt), + _c(c), + _dkLen(dkLen) + { + _result.reserve(_dkLen + PRF_DIGEST_SIZE); + } + + ~PBKDF2Engine() + { + } + + std::size_t digestLength() const + { + return _dkLen; + } + + void reset() + { + _p.clear(); + _result.clear(); + } + + const DigestEngine::Digest& digest() + { + Poco::UInt32 i = 1; + while (_result.size() < _dkLen) + { + f(i++); + } + _result.resize(_dkLen); + return _result; + } + +protected: + void updateImpl(const void* data, std::size_t length) + { + _p.append(reinterpret_cast<const char*>(data), length); + } + + void f(Poco::UInt32 i) + { + PRF prf(_p); + prf.update(_s); + Poco::UInt32 iBE = Poco::ByteOrder::toBigEndian(i); + prf.update(&iBE, sizeof(iBE)); + Poco::DigestEngine::Digest up = prf.digest(); + Poco::DigestEngine::Digest ux = up; + poco_assert_dbg(ux.size() == PRF_DIGEST_SIZE); + for (unsigned k = 1; k < _c; k++) + { + prf.reset(); + prf.update(&up[0], up.size()); + Poco::DigestEngine::Digest u = prf.digest(); + poco_assert_dbg(u.size() == PRF_DIGEST_SIZE); + for (int ui = 0; ui < PRF_DIGEST_SIZE; ui++) + { + ux[ui] ^= u[ui]; + } + std::swap(up, u); + } + _result.insert(_result.end(), ux.begin(), ux.end()); + } + +private: + PBKDF2Engine(); + PBKDF2Engine(const PBKDF2Engine&); + PBKDF2Engine& operator = (const PBKDF2Engine&); + + std::string _p; + std::string _s; + unsigned _c; + Poco::UInt32 _dkLen; + DigestEngine::Digest _result; +}; + + +} // namespace Poco + + +#endif // Foundation_PBKDF2Engine_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Path.h b/contrib/libs/poco/Foundation/include/Poco/Path.h new file mode 100644 index 0000000000..c50c1a1a86 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Path.h @@ -0,0 +1,501 @@ +// +// Path.h +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the Path class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Path_INCLUDED +#define Foundation_Path_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> + + +namespace Poco { + + +class Foundation_API Path + /// This class represents filesystem paths in a + /// platform-independent manner. + /// Unix, Windows and OpenVMS all use a different + /// syntax for filesystem paths. + /// This class can work with all three formats. + /// A path is made up of an optional node name + /// (only Windows and OpenVMS), an optional + /// device name (also only Windows and OpenVMS), + /// a list of directory names and an optional + /// filename. +{ +public: + enum Style + { + PATH_UNIX, /// Unix-style path + PATH_WINDOWS, /// Windows-style path + PATH_VMS, /// VMS-style path + PATH_NATIVE, /// The current platform's native style + PATH_GUESS /// Guess the style by examining the path + }; + + typedef std::vector<std::string> StringVec; + + Path(); + /// Creates an empty relative path. + + Path(bool absolute); + /// Creates an empty absolute or relative path. + + Path(const char* path); + /// Creates a path from a string. + + Path(const char* path, Style style); + /// Creates a path from a string. + + Path(const std::string& path); + /// Creates a path from a string. + + Path(const std::string& path, Style style); + /// Creates a path from a string. + + Path(const Path& path); + /// Copy constructor + + Path(const Path& parent, const std::string& fileName); + /// Creates a path from a parent path and a filename. + /// The parent path is expected to reference a directory. + + Path(const Path& parent, const char* fileName); + /// Creates a path from a parent path and a filename. + /// The parent path is expected to reference a directory. + + Path(const Path& parent, const Path& relative); + /// Creates a path from a parent path and a relative path. + /// The parent path is expected to reference a directory. + /// The relative path is appended to the parent path. + + ~Path(); + /// Destroys the Path. + + Path& operator = (const Path& path); + /// Assignment operator. + + Path& operator = (const std::string& path); + /// Assigns a string containing a path in native format. + + Path& operator = (const char* path); + /// Assigns a string containing a path in native format. + + void swap(Path& path); + /// Swaps the path with another one. + + Path& assign(const std::string& path); + /// Assigns a string containing a path in native format. + + Path& assign(const std::string& path, Style style); + /// Assigns a string containing a path. + + Path& assign(const Path& path); + /// Assigns the given path. + + Path& assign(const char* path); + /// Assigns a string containing a path. + + std::string toString() const; + /// Returns a string containing the path in native format. + + std::string toString(Style style) const; + /// Returns a string containing the path in the given format. + + Path& parse(const std::string& path); + /// Same as assign(). + + Path& parse(const std::string& path, Style style); + /// Assigns a string containing a path. + + bool tryParse(const std::string& path); + /// Tries to interpret the given string as a path + /// in native format. + /// If the path is syntactically valid, assigns the + /// path and returns true. Otherwise leaves the + /// object unchanged and returns false. + + bool tryParse(const std::string& path, Style style); + /// Tries to interpret the given string as a path, + /// according to the given style. + /// If the path is syntactically valid, assigns the + /// path and returns true. Otherwise leaves the + /// object unchanged and returns false. + + Path& parseDirectory(const std::string& path); + /// The resulting path always refers to a directory and + /// the filename part is empty. + + Path& parseDirectory(const std::string& path, Style style); + /// The resulting path always refers to a directory and + /// the filename part is empty. + + Path& makeDirectory(); + /// If the path contains a filename, the filename is appended + /// to the directory list and cleared. Thus the resulting path + /// always refers to a directory. + + Path& makeFile(); + /// If the path contains no filename, the last directory + /// becomes the filename. + + Path& makeParent(); + /// Makes the path refer to its parent. + + Path& makeAbsolute(); + /// Makes the path absolute if it is relative. + /// The current working directory is taken as base directory. + + Path& makeAbsolute(const Path& base); + /// Makes the path absolute if it is relative. + /// The given path is taken as base. + + Path& append(const Path& path); + /// Appends the given path. + + Path& resolve(const Path& path); + /// Resolves the given path agains the current one. + /// + /// If the given path is absolute, it replaces the current one. + /// Otherwise, the relative path is appended to the current path. + + bool isAbsolute() const; + /// Returns true iff the path is absolute. + + bool isRelative() const; + /// Returns true iff the path is relative. + + bool isDirectory() const; + /// Returns true iff the path references a directory + /// (the filename part is empty). + + bool isFile() const; + /// Returns true iff the path references a file + /// (the filename part is not empty). + + Path& setNode(const std::string& node); + /// Sets the node name. + /// Setting a non-empty node automatically makes + /// the path an absolute one. + + const std::string& getNode() const; + /// Returns the node name. + + Path& setDevice(const std::string& device); + /// Sets the device name. + /// Setting a non-empty device automatically makes + /// the path an absolute one. + + const std::string& getDevice() const; + /// Returns the device name. + + int depth() const; + /// Returns the number of directories in the directory list. + + const std::string& directory(int n) const; + /// Returns the n'th directory in the directory list. + /// If n == depth(), returns the filename. + + const std::string& operator [] (int n) const; + /// Returns the n'th directory in the directory list. + /// If n == depth(), returns the filename. + + Path& pushDirectory(const std::string& dir); + /// Adds a directory to the directory list. + + Path& popDirectory(); + /// Removes the last directory from the directory list. + + Path& popFrontDirectory(); + /// Removes the first directory from the directory list. + + Path& setFileName(const std::string& name); + /// Sets the filename. + + const std::string& getFileName() const; + /// Returns the filename. + + Path& setBaseName(const std::string& name); + /// Sets the basename part of the filename and + /// does not change the extension. + + std::string getBaseName() const; + /// Returns the basename (the filename sans + /// extension) of the path. + + Path& setExtension(const std::string& extension); + /// Sets the filename extension. + + std::string getExtension() const; + /// Returns the filename extension. + + const std::string& version() const; + /// Returns the file version. VMS only. + + Path& clear(); + /// Clears all components. + + Path parent() const; + /// Returns a path referring to the path's + /// directory. + + Path absolute() const; + /// Returns an absolute variant of the path, + /// taking the current working directory as base. + + Path absolute(const Path& base) const; + /// Returns an absolute variant of the path, + /// taking the given path as base. + + static Path forDirectory(const std::string& path); + /// Creates a path referring to a directory. + + static Path forDirectory(const std::string& path, Style style); + /// Creates a path referring to a directory. + + static char separator(); + /// Returns the platform's path name separator, which separates + /// the components (names) in a path. + /// + /// On Unix systems, this is the slash '/'. On Windows systems, + /// this is the backslash '\'. On OpenVMS systems, this is the + /// period '.'. + + static char pathSeparator(); + /// Returns the platform's path separator, which separates + /// single paths in a list of paths. + /// + /// On Unix systems, this is the colon ':'. On Windows systems, + /// this is the semicolon ';'. On OpenVMS systems, this is the + /// comma ','. + + static std::string current(); + /// Returns the current working directory. + + static std::string home(); + /// Returns the user's home directory. + + static std::string configHome(); + /// Returns the user's config directory. + /// + /// On Unix systems, this is the '~/.config/'. On Windows systems, + /// this is '%APPDATA%'. + + static std::string dataHome(); + /// Returns the user's data directory. + /// + /// On Unix systems, this is the '~/.local/share/'. On Windows systems, + /// this is '%APPDATA%'. + + static std::string tempHome(); + /// Returns the user's temp directory. + /// + /// On Unix systems, this is the '~/.local/temp/'. + + static std::string cacheHome(); + /// Returns the user's cache directory. + /// + /// On Unix systems, this is the '~/.cache/'. On Windows systems, + /// this is '%APPDATA%'. + + static std::string temp(); + /// Returns the temporary directory. + + static std::string config(); + /// Returns the systemwide config directory. + /// + /// On Unix systems, this is the '/etc/'. + + static std::string null(); + /// Returns the name of the null device. + + static std::string expand(const std::string& path); + /// Expands all environment variables contained in the path. + /// + /// On Unix, a tilde as first character in the path is + /// replaced with the path to user's home directory. + + static void listRoots(std::vector<std::string>& roots); + /// Fills the vector with all filesystem roots available on the + /// system. On Unix, there is exactly one root, "/". + /// On Windows, the roots are the drive letters. + /// On OpenVMS, the roots are the mounted disks. + + static bool find(StringVec::const_iterator it, StringVec::const_iterator end, const std::string& name, Path& path); + /// Searches the file with the given name in the locations (paths) specified + /// by it and end. A relative path may be given in name. + /// + /// If the file is found in one of the locations, the complete + /// path of the file is stored in the path given as argument and true is returned. + /// Otherwise false is returned and the path argument remains unchanged. + + static bool find(const std::string& pathList, const std::string& name, Path& path); + /// Searches the file with the given name in the locations (paths) specified + /// in pathList. The paths in pathList must be delimited by the platform's + /// path separator (see pathSeparator()). A relative path may be given in name. + /// + /// If the file is found in one of the locations, the complete + /// path of the file is stored in the path given as argument and true is returned. + /// Otherwise false is returned and the path argument remains unchanged. + + static std::string transcode(const std::string& path); + /// On Windows, if POCO has been compiled with Windows UTF-8 support + /// (POCO_WIN32_UTF8), this function converts a string (usually containing a path) + /// encoded in UTF-8 into a string encoded in the current Windows code page. + /// + /// This function should be used for every string passed as a file name to + /// a string stream or fopen(). + /// + /// On all other platforms, or if POCO has not been compiled with Windows UTF-8 + /// support, this function returns the string unchanged. + +protected: + void parseUnix(const std::string& path); + void parseWindows(const std::string& path); + void parseVMS(const std::string& path); + void parseGuess(const std::string& path); + std::string buildUnix() const; + std::string buildWindows() const; + std::string buildVMS() const; + +private: + std::string _node; + std::string _device; + std::string _name; + std::string _version; + StringVec _dirs; + bool _absolute; +}; + + +// +// inlines +// +inline bool Path::isAbsolute() const +{ + return _absolute; +} + + +inline bool Path::isRelative() const +{ + return !_absolute; +} + + +inline bool Path::isDirectory() const +{ + return _name.empty(); +} + + +inline bool Path::isFile() const +{ + return !_name.empty(); +} + + +inline Path& Path::parse(const std::string& path) +{ + return assign(path); +} + + +inline Path& Path::parse(const std::string& path, Style style) +{ + return assign(path, style); +} + + +inline const std::string& Path::getNode() const +{ + return _node; +} + + +inline const std::string& Path::getDevice() const +{ + return _device; +} + + +inline const std::string& Path::getFileName() const +{ + return _name; +} + + +inline int Path::depth() const +{ + return int(_dirs.size()); +} + + +inline const std::string& Path::version() const +{ + return _version; +} + + +inline Path Path::forDirectory(const std::string& path) +{ + Path p; + return p.parseDirectory(path); +} + + +inline Path Path::forDirectory(const std::string& path, Style style) +{ + Path p; + return p.parseDirectory(path, style); +} + + +inline char Path::separator() +{ +#if defined(POCO_OS_FAMILY_VMS) + return '.'; +#elif defined(POCO_OS_FAMILY_WINDOWS) + return '\\'; +#else + return '/'; +#endif +} + + +inline char Path::pathSeparator() +{ +#if defined(POCO_OS_FAMILY_VMS) + return ','; +#elif defined(POCO_OS_FAMILY_WINDOWS) + return ';'; +#else + return ':'; +#endif +} + + +inline void swap(Path& p1, Path& p2) +{ + p1.swap(p2); +} + + +} // namespace Poco + + +#endif // Foundation_Path_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Path_UNIX.h b/contrib/libs/poco/Foundation/include/Poco/Path_UNIX.h new file mode 100644 index 0000000000..50a6478b92 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Path_UNIX.h @@ -0,0 +1,48 @@ +// +// Path_UNIX.h +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the PathImpl class fo rUnix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Path_UNIX_INCLUDED +#define Foundation_Path_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> + + +namespace Poco { + + +class PathImpl +{ +public: + static std::string currentImpl(); + static std::string homeImpl(); + static std::string configHomeImpl(); + static std::string dataHomeImpl(); + static std::string tempHomeImpl(); + static std::string cacheHomeImpl(); + static std::string tempImpl(); + static std::string configImpl(); + static std::string nullImpl(); + static std::string expandImpl(const std::string& path); + static void listRootsImpl(std::vector<std::string>& roots); +}; + + +} // namespace Poco + + +#endif // Foundation_Path_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Path_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/Path_WIN32.h new file mode 100644 index 0000000000..02a3a5b281 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Path_WIN32.h @@ -0,0 +1,49 @@ +// +// Path_WIN32.h +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the PathImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Path_WIN32_INCLUDED +#define Foundation_Path_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> + + +namespace Poco { + + +class Foundation_API PathImpl +{ +public: + static std::string currentImpl(); + static std::string homeImpl(); + static std::string configHomeImpl(); + static std::string dataHomeImpl(); + static std::string cacheHomeImpl(); + static std::string tempHomeImpl(); + static std::string tempImpl(); + static std::string configImpl(); + static std::string nullImpl(); + static std::string systemImpl(); + static std::string expandImpl(const std::string& path); + static void listRootsImpl(std::vector<std::string>& roots); +}; + + +} // namespace Poco + + +#endif // Foundation_Path_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Path_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/Path_WIN32U.h new file mode 100644 index 0000000000..94fca2b0a7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Path_WIN32U.h @@ -0,0 +1,54 @@ +// +// Path_WIN32U.h +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the PathImpl class for WIN32. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Path_WIN32U_INCLUDED +#define Foundation_Path_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> + + +namespace Poco { + + +class Foundation_API PathImpl +{ +public: + static std::string currentImpl(); + static std::string homeImpl(); + static std::string configHomeImpl(); + static std::string dataHomeImpl(); + static std::string cacheHomeImpl(); + static std::string tempHomeImpl(); + static std::string tempImpl(); + static std::string configImpl(); + static std::string nullImpl(); + static std::string systemImpl(); + static std::string expandImpl(const std::string& path); + static void listRootsImpl(std::vector<std::string>& roots); + + enum + { + MAX_PATH_LEN = 32767 + }; +}; + + +} // namespace Poco + + +#endif // Foundation_Path_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Path_WINCE.h b/contrib/libs/poco/Foundation/include/Poco/Path_WINCE.h new file mode 100644 index 0000000000..a32e3316ad --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Path_WINCE.h @@ -0,0 +1,54 @@ +// +// Path_WINCE.h +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the PathImpl class for WIN32. +// +// Copyright (c) 2006-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Path_WINCE_INCLUDED +#define Foundation_Path_WINCE_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> + + +namespace Poco { + + +class Foundation_API PathImpl +{ +public: + static std::string currentImpl(); + static std::string homeImpl(); + static std::string configHomeImpl(); + static std::string dataHomeImpl(); + static std::string cacheHomeImpl(); + static std::string tempHomeImpl(); + static std::string tempImpl(); + static std::string configImpl(); + static std::string nullImpl(); + static std::string systemImpl(); + static std::string expandImpl(const std::string& path); + static void listRootsImpl(std::vector<std::string>& roots); + + enum + { + MAX_PATH_LEN = 32767 + }; +}; + + +} // namespace Poco + + +#endif // Foundation_Path_WINCE_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PatternFormatter.h b/contrib/libs/poco/Foundation/include/Poco/PatternFormatter.h new file mode 100644 index 0000000000..cdbb0f08db --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PatternFormatter.h @@ -0,0 +1,148 @@ +// +// PatternFormatter.h +// +// Library: Foundation +// Package: Logging +// Module: PatternFormatter +// +// Definition of the PatternFormatter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PatternFormatter_INCLUDED +#define Foundation_PatternFormatter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Formatter.h" +#include "Poco/Message.h" + +#include <vector> + +namespace Poco { + + +class Foundation_API PatternFormatter: public Formatter + /// This Formatter allows for custom formatting of + /// log messages based on format patterns. + /// + /// The format pattern is used as a template to format the message and + /// is copied character by character except for the following special characters, + /// which are replaced by the corresponding value. + /// + /// * %s - message source + /// * %t - message text + /// * %l - message priority level (1 .. 7) + /// * %p - message priority (Fatal, Critical, Error, Warning, Notice, Information, Debug, Trace) + /// * %q - abbreviated message priority (F, C, E, W, N, I, D, T) + /// * %P - message process identifier + /// * %T - message thread name + /// * %I - message thread identifier (numeric) + /// * %N - node or host name + /// * %U - message source file path (empty string if not set) + /// * %u - message source line number (0 if not set) + /// * %w - message date/time abbreviated weekday (Mon, Tue, ...) + /// * %W - message date/time full weekday (Monday, Tuesday, ...) + /// * %b - message date/time abbreviated month (Jan, Feb, ...) + /// * %B - message date/time full month (January, February, ...) + /// * %d - message date/time zero-padded day of month (01 .. 31) + /// * %e - message date/time day of month (1 .. 31) + /// * %f - message date/time space-padded day of month ( 1 .. 31) + /// * %m - message date/time zero-padded month (01 .. 12) + /// * %n - message date/time month (1 .. 12) + /// * %o - message date/time space-padded month ( 1 .. 12) + /// * %y - message date/time year without century (70) + /// * %Y - message date/time year with century (1970) + /// * %H - message date/time hour (00 .. 23) + /// * %h - message date/time hour (00 .. 12) + /// * %a - message date/time am/pm + /// * %A - message date/time AM/PM + /// * %M - message date/time minute (00 .. 59) + /// * %S - message date/time second (00 .. 59) + /// * %i - message date/time millisecond (000 .. 999) + /// * %c - message date/time centisecond (0 .. 9) + /// * %F - message date/time fractional seconds/microseconds (000000 - 999999) + /// * %z - time zone differential in ISO 8601 format (Z or +NN.NN) + /// * %Z - time zone differential in RFC format (GMT or +NNNN) + /// * %L - convert time to local time (must be specified before any date/time specifier; does not itself output anything) + /// * %E - epoch time (UTC, seconds since midnight, January 1, 1970) + /// * %v[width] - the message source (%s) but text length is padded/cropped to 'width' + /// * %[name] - the value of the message parameter with the given name + /// * %% - percent sign + +{ +public: + PatternFormatter(); + /// Creates a PatternFormatter. + /// The format pattern must be specified with + /// a call to setProperty. + + PatternFormatter(const std::string& format); + /// Creates a PatternFormatter that uses the + /// given format pattern. + + ~PatternFormatter(); + /// Destroys the PatternFormatter. + + void format(const Message& msg, std::string& text); + /// Formats the message according to the specified + /// format pattern and places the result in text. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name to the given value. + /// + /// The following properties are supported: + /// + /// * pattern: The format pattern. See the PatternFormatter class + /// for details. + /// * times: Specifies whether times are adjusted for local time + /// or taken as they are in UTC. Supported values are "local" and "UTC". + /// + /// If any other property name is given, a PropertyNotSupported + /// exception is thrown. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name or + /// throws a PropertyNotSupported exception if the given + /// name is not recognized. + + static const std::string PROP_PATTERN; + static const std::string PROP_TIMES; + +protected: + static const std::string& getPriorityName(int); + /// Returns a string for the given priority value. + +private: + struct PatternAction + { + PatternAction(): key(0), length(0) + { + } + + char key; + int length; + std::string property; + std::string prepend; + }; + + void parsePattern(); + /// Will parse the _pattern string into the vector of PatternActions, + /// which contains the message key, any text that needs to be written first + /// a proprety in case of %[] and required length. + + std::vector<PatternAction> _patternActions; + bool _localTime; + std::string _pattern; +}; + + +} // namespace Poco + + +#endif // Foundation_PatternFormatter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Pipe.h b/contrib/libs/poco/Foundation/include/Poco/Pipe.h new file mode 100644 index 0000000000..89704b12bc --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Pipe.h @@ -0,0 +1,142 @@ +// +// Pipe.h +// +// Library: Foundation +// Package: Processes +// Module: Pipe +// +// Definition of the Pipe class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Pipe_INCLUDED +#define Foundation_Pipe_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/PipeImpl.h" + + +namespace Poco { + + +class Foundation_API Pipe + /// This class implements an anonymous pipe. + /// + /// Pipes are a common method of inter-process communication - + /// on Unix, pipes are the oldest form of IPC. + /// + /// A pipe is a half-duplex communication channel, which means + /// that data only flows in one direction. + /// Pipes have a read-end and a write-end. One process writes to + /// the pipe and another process reads the data written by + /// its peer. + /// Read and write operations are always synchronous. A read will + /// block until data is available and a write will block until + /// the reader reads the data. + /// + /// The sendBytes() and readBytes() methods of Pipe are usually + /// used through a PipeOutputStream or PipeInputStream and are + /// not called directly. + /// + /// Pipe objects have value semantics; the actual work is delegated + /// to a reference-counted PipeImpl object. +{ +public: + typedef PipeImpl::Handle Handle; /// The read/write handle or file descriptor. + + enum CloseMode /// used by close() + { + CLOSE_READ = 0x01, /// Close reading end of pipe. + CLOSE_WRITE = 0x02, /// Close writing end of pipe. + CLOSE_BOTH = 0x03 /// Close both ends of pipe. + }; + + Pipe(); + /// Creates the Pipe. + /// + /// Throws a CreateFileException if the pipe cannot be + /// created. + + Pipe(const Pipe& pipe); + /// Creates the Pipe using the PipeImpl from another one. + + ~Pipe(); + /// Closes and destroys the Pipe. + + Pipe& operator = (const Pipe& pipe); + /// Releases the Pipe's PipeImpl and assigns another one. + + int writeBytes(const void* buffer, int length); + /// Sends the contents of the given buffer through + /// the pipe. Blocks until the receiver is ready + /// to read the data. + /// + /// Returns the number of bytes sent. + /// + /// Throws a WriteFileException if the data cannot be written. + + int readBytes(void* buffer, int length); + /// Receives data from the pipe and stores it + /// in buffer. Up to length bytes are received. + /// Blocks until data becomes available. + /// + /// Returns the number of bytes received, or 0 + /// if the pipe has been closed. + /// + /// Throws a ReadFileException if nothing can be read. + + Handle readHandle() const; + /// Returns the read handle or file descriptor + /// for the Pipe. For internal use only. + + Handle writeHandle() const; + /// Returns the write handle or file descriptor + /// for the Pipe. For internal use only. + + void close(CloseMode mode = CLOSE_BOTH); + /// Depending on the argument, closes either the + /// reading end, the writing end, or both ends + /// of the Pipe. + +private: + PipeImpl* _pImpl; +}; + + +// +// inlines +// +inline int Pipe::writeBytes(const void* buffer, int length) +{ + return _pImpl->writeBytes(buffer, length); +} + + +inline int Pipe::readBytes(void* buffer, int length) +{ + return _pImpl->readBytes(buffer, length); +} + + +inline Pipe::Handle Pipe::readHandle() const +{ + return _pImpl->readHandle(); +} + + +inline Pipe::Handle Pipe::writeHandle() const +{ + return _pImpl->writeHandle(); +} + + +} // namespace Poco + + +#endif // Foundation_Pipe_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PipeImpl.h b/contrib/libs/poco/Foundation/include/Poco/PipeImpl.h new file mode 100644 index 0000000000..b0b7183705 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PipeImpl.h @@ -0,0 +1,37 @@ +// +// PipeImpl.h +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Definition of the PipeImpl class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PipeImpl_INCLUDED +#define Foundation_PipeImpl_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#if defined(_WIN32_WCE) +#include "PipeImpl_DUMMY.h" +#else +#include "Poco/PipeImpl_WIN32.h" +#endif +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/PipeImpl_POSIX.h" +#else +#include "Poco/PipeImpl_DUMMY.h" +#endif + + +#endif // Foundation_PipeImpl_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PipeImpl_DUMMY.h b/contrib/libs/poco/Foundation/include/Poco/PipeImpl_DUMMY.h new file mode 100644 index 0000000000..e7616ff6c2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PipeImpl_DUMMY.h @@ -0,0 +1,49 @@ +// +// PipeImpl_DUMMY.h +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Definition of the PipeImpl_DUMMY class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PipeImpl_DUMMY_INCLUDED +#define Foundation_PipeImpl_DUMMY_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Foundation_API PipeImpl: public RefCountedObject + /// A dummy implementation of PipeImpl for platforms + /// that do not support pipes. +{ +public: + typedef int Handle; + + PipeImpl(); + ~PipeImpl(); + int writeBytes(const void* buffer, int length); + int readBytes(void* buffer, int length); + Handle readHandle() const; + Handle writeHandle() const; + void closeRead(); + void closeWrite(); +}; + + +} // namespace Poco + + +#endif // Foundation_PipeImpl_DUMMY_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PipeImpl_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/PipeImpl_POSIX.h new file mode 100644 index 0000000000..448e616efe --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PipeImpl_POSIX.h @@ -0,0 +1,53 @@ +// +// PipeImpl_POSIX.h +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Definition of the PipeImpl class for POSIX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PipeImpl_POSIX_INCLUDED +#define Foundation_PipeImpl_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Foundation_API PipeImpl: public RefCountedObject + /// A dummy implementation of PipeImpl for platforms + /// that do not support pipes. +{ +public: + typedef int Handle; + + PipeImpl(); + ~PipeImpl(); + int writeBytes(const void* buffer, int length); + int readBytes(void* buffer, int length); + Handle readHandle() const; + Handle writeHandle() const; + void closeRead(); + void closeWrite(); + +private: + int _readfd; + int _writefd; +}; + + +} // namespace Poco + + +#endif // Foundation_PipeImpl_POSIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PipeImpl_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/PipeImpl_WIN32.h new file mode 100644 index 0000000000..936817987a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PipeImpl_WIN32.h @@ -0,0 +1,54 @@ +// +// PipeImpl_WIN32.h +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Definition of the PipeImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PipeImpl_WIN32_INCLUDED +#define Foundation_PipeImpl_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API PipeImpl: public RefCountedObject + /// A dummy implementation of PipeImpl for platforms + /// that do not support pipes. +{ +public: + typedef HANDLE Handle; + + PipeImpl(); + ~PipeImpl(); + int writeBytes(const void* buffer, int length); + int readBytes(void* buffer, int length); + Handle readHandle() const; + Handle writeHandle() const; + void closeRead(); + void closeWrite(); + +private: + HANDLE _readHandle; + HANDLE _writeHandle; +}; + + +} // namespace Poco + + +#endif // Foundation_PipeImpl_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PipeStream.h b/contrib/libs/poco/Foundation/include/Poco/PipeStream.h new file mode 100644 index 0000000000..96b602aeab --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PipeStream.h @@ -0,0 +1,120 @@ +// +// PipeStream.h +// +// Library: Foundation +// Package: Processes +// Module: PipeStream +// +// Definition of the PipeStream class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PipeStream_INCLUDED +#define Foundation_PipeStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Pipe.h" +#include "Poco/BufferedStreamBuf.h" +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API PipeStreamBuf: public BufferedStreamBuf + /// This is the streambuf class used for reading from and writing to a Pipe. +{ +public: + typedef BufferedStreamBuf::openmode openmode; + + PipeStreamBuf(const Pipe& pipe, openmode mode); + /// Creates a PipeStreamBuf with the given Pipe. + + ~PipeStreamBuf(); + /// Destroys the PipeStreamBuf. + + void close(); + /// Closes the pipe. + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024 + }; + + Pipe _pipe; +}; + + +class Foundation_API PipeIOS: public virtual std::ios + /// The base class for PipeInputStream and + /// PipeOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + PipeIOS(const Pipe& pipe, openmode mode); + /// Creates the PipeIOS with the given Pipe. + + ~PipeIOS(); + /// Destroys the PipeIOS. + /// + /// Flushes the buffer, but does not close the pipe. + + PipeStreamBuf* rdbuf(); + /// Returns a pointer to the internal PipeStreamBuf. + + void close(); + /// Flushes the stream and closes the pipe. + +protected: + PipeStreamBuf _buf; +}; + + +class Foundation_API PipeOutputStream: public PipeIOS, public std::ostream + /// An output stream for writing to a Pipe. +{ +public: + PipeOutputStream(const Pipe& pipe); + /// Creates the PipeOutputStream with the given Pipe. + + ~PipeOutputStream(); + /// Destroys the PipeOutputStream. + /// + /// Flushes the buffer, but does not close the pipe. +}; + + +class Foundation_API PipeInputStream: public PipeIOS, public std::istream + /// An input stream for reading from a Pipe. + /// + /// Using formatted input from a PipeInputStream + /// is not recommended, due to the read-ahead behavior of + /// istream with formatted reads. +{ +public: + PipeInputStream(const Pipe& pipe); + /// Creates the PipeInputStream with the given Pipe. + + ~PipeInputStream(); + /// Destroys the PipeInputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_PipeStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Platform.h b/contrib/libs/poco/Foundation/include/Poco/Platform.h new file mode 100644 index 0000000000..799db417e7 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Platform.h @@ -0,0 +1,284 @@ +// +// Platform.h +// +// Library: Foundation +// Package: Core +// Module: Platform +// +// Platform and architecture identification macros. +// +// NOTE: This file may be included from both C++ and C code, so it +// must not contain any C++ specific things. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Platform_INCLUDED +#define Foundation_Platform_INCLUDED + + +// +// Platform Identification +// +#define POCO_OS_FREE_BSD 0x0001 +#define POCO_OS_AIX 0x0002 +#define POCO_OS_HPUX 0x0003 +#define POCO_OS_TRU64 0x0004 +#define POCO_OS_LINUX 0x0005 +#define POCO_OS_MAC_OS_X 0x0006 +#define POCO_OS_NET_BSD 0x0007 +#define POCO_OS_OPEN_BSD 0x0008 +#define POCO_OS_IRIX 0x0009 +#define POCO_OS_SOLARIS 0x000a +#define POCO_OS_QNX 0x000b +#define POCO_OS_VXWORKS 0x000c +#define POCO_OS_CYGWIN 0x000d +#define POCO_OS_NACL 0x000e +#define POCO_OS_ANDROID 0x000f +#define POCO_OS_UNKNOWN_UNIX 0x00ff +#define POCO_OS_WINDOWS_NT 0x1001 +#define POCO_OS_WINDOWS_CE 0x1011 +#define POCO_OS_VMS 0x2001 + + +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS_FAMILY_BSD 1 + #define POCO_OS POCO_OS_FREE_BSD +#elif defined(_AIX) || defined(__TOS_AIX__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_AIX +#elif defined(hpux) || defined(_hpux) || defined(__hpux) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_HPUX +#elif defined(__digital__) || defined(__osf__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_TRU64 +#elif defined(__NACL__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_NACL +#elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__TOS_LINUX__) || defined(EMSCRIPTEN) + #define POCO_OS_FAMILY_UNIX 1 + #if defined(__ANDROID__) + #define POCO_OS POCO_OS_ANDROID + #else + #define POCO_OS POCO_OS_LINUX + #endif +#elif defined(__APPLE__) || defined(__TOS_MACOS__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS_FAMILY_BSD 1 + #define POCO_OS POCO_OS_MAC_OS_X +#elif defined(__NetBSD__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS_FAMILY_BSD 1 + #define POCO_OS POCO_OS_NET_BSD +#elif defined(__OpenBSD__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS_FAMILY_BSD 1 + #define POCO_OS POCO_OS_OPEN_BSD +#elif defined(sgi) || defined(__sgi) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_IRIX +#elif defined(sun) || defined(__sun) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_SOLARIS +#elif defined(__QNX__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_QNX +#elif defined(__CYGWIN__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_CYGWIN +#elif defined(POCO_VXWORKS) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_VXWORKS +#elif defined(unix) || defined(__unix) || defined(__unix__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_UNKNOWN_UNIX +#elif defined(_WIN32_WCE) + #define POCO_OS_FAMILY_WINDOWS 1 + #define POCO_OS POCO_OS_WINDOWS_CE +#elif defined(_WIN32) || defined(_WIN64) + #define POCO_OS_FAMILY_WINDOWS 1 + #define POCO_OS POCO_OS_WINDOWS_NT +#elif defined(__VMS) + #define POCO_OS_FAMILY_VMS 1 + #define POCO_OS POCO_OS_VMS +#endif + + +#if !defined(POCO_OS) + #error "Unknown Platform." +#endif + + +// +// Hardware Architecture and Byte Order +// +#define POCO_ARCH_ALPHA 0x01 +#define POCO_ARCH_IA32 0x02 +#define POCO_ARCH_IA64 0x03 +#define POCO_ARCH_MIPS 0x04 +#define POCO_ARCH_HPPA 0x05 +#define POCO_ARCH_PPC 0x06 +#define POCO_ARCH_POWER 0x07 +#define POCO_ARCH_SPARC 0x08 +#define POCO_ARCH_AMD64 0x09 +#define POCO_ARCH_ARM 0x0a +#define POCO_ARCH_M68K 0x0b +#define POCO_ARCH_S390 0x0c +#define POCO_ARCH_SH 0x0d +#define POCO_ARCH_NIOS2 0x0e +#define POCO_ARCH_AARCH64 0x0f +#define POCO_ARCH_ARM64 0x0f // same as POCO_ARCH_AARCH64 +#define POCO_ARCH_RISCV64 0x10 + + +#if defined(__ALPHA) || defined(__alpha) || defined(__alpha__) || defined(_M_ALPHA) + #define POCO_ARCH POCO_ARCH_ALPHA + #define POCO_ARCH_LITTLE_ENDIAN 1 +#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(EMSCRIPTEN) + #define POCO_ARCH POCO_ARCH_IA32 + #define POCO_ARCH_LITTLE_ENDIAN 1 +#elif defined(_IA64) || defined(__IA64__) || defined(__ia64__) || defined(__ia64) || defined(_M_IA64) + #define POCO_ARCH POCO_ARCH_IA64 + #if defined(hpux) || defined(_hpux) + #define POCO_ARCH_BIG_ENDIAN 1 + #else + #define POCO_ARCH_LITTLE_ENDIAN 1 + #endif +#elif defined(__x86_64__) || defined(_M_X64) + #define POCO_ARCH POCO_ARCH_AMD64 + #define POCO_ARCH_LITTLE_ENDIAN 1 +#elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(_M_MRX000) + #define POCO_ARCH POCO_ARCH_MIPS + #if defined(POCO_OS_FAMILY_WINDOWS) + // Is this OK? Supports windows only little endian?? + #define POCO_ARCH_LITTLE_ENDIAN 1 + #elif defined(__MIPSEB__) || defined(_MIPSEB) || defined(__MIPSEB) + #define POCO_ARCH_BIG_ENDIAN 1 + #elif defined(__MIPSEL__) || defined(_MIPSEL) || defined(__MIPSEL) + #define POCO_ARCH_LITTLE_ENDIAN 1 + #else + #error "MIPS but neither MIPSEL nor MIPSEB?" + #endif +#elif defined(__hppa) || defined(__hppa__) + #define POCO_ARCH POCO_ARCH_HPPA + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__PPC) || defined(__POWERPC__) || defined(__powerpc) || defined(__PPC__) || \ + defined(__powerpc__) || defined(__ppc__) || defined(__ppc) || defined(_ARCH_PPC) || defined(_M_PPC) + #define POCO_ARCH POCO_ARCH_PPC + #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) + #define POCO_ARCH_LITTLE_ENDIAN 1 + #else + #define POCO_ARCH_BIG_ENDIAN 1 + #endif +#elif defined(_POWER) || defined(_ARCH_PWR) || defined(_ARCH_PWR2) || defined(_ARCH_PWR3) || \ + defined(_ARCH_PWR4) || defined(__THW_RS6000) + #define POCO_ARCH POCO_ARCH_POWER + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__sparc__) || defined(__sparc) || defined(sparc) + #define POCO_ARCH POCO_ARCH_SPARC + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__arm__) || defined(__arm) || defined(ARM) || defined(_ARM_) || defined(__ARM__) || defined(_M_ARM) + #define POCO_ARCH POCO_ARCH_ARM + #if defined(__ARMEB__) + #define POCO_ARCH_BIG_ENDIAN 1 + #else + #define POCO_ARCH_LITTLE_ENDIAN 1 + #endif +#elif defined(__arm64__) || defined(__arm64) + #define POCO_ARCH POCO_ARCH_ARM64 + #if defined(__ARMEB__) + #define POCO_ARCH_BIG_ENDIAN 1 + #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + #define POCO_ARCH_BIG_ENDIAN 1 + #else + #define POCO_ARCH_LITTLE_ENDIAN 1 + #endif +#elif defined(__m68k__) + #define POCO_ARCH POCO_ARCH_M68K + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__s390__) + #define POCO_ARCH POCO_ARCH_S390 + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__sh__) || defined(__sh) || defined(SHx) || defined(_SHX_) + #define POCO_ARCH POCO_ARCH_SH + #if defined(__LITTLE_ENDIAN__) || (POCO_OS == POCO_OS_WINDOWS_CE) + #define POCO_ARCH_LITTLE_ENDIAN 1 + #else + #define POCO_ARCH_BIG_ENDIAN 1 + #endif +#elif defined (nios2) || defined(__nios2) || defined(__nios2__) + #define POCO_ARCH POCO_ARCH_NIOS2 + #if defined(__nios2_little_endian) || defined(nios2_little_endian) || defined(__nios2_little_endian__) + #define POCO_ARCH_LITTLE_ENDIAN 1 + #else + #define POCO_ARCH_BIG_ENDIAN 1 + #endif +#elif defined(__AARCH64EL__) + #define POCO_ARCH POCO_ARCH_AARCH64 + #define POCO_ARCH_LITTLE_ENDIAN 1 +#elif defined(__AARCH64EB__) + #define POCO_ARCH POCO_ARCH_AARCH64 + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__riscv) && (__riscv_xlen == 64) + #define POCO_ARCH POCO_ARCH_RISCV64 + #define POCO_ARCH_LITTLE_ENDIAN 1 +#endif + + +#if defined(__clang__) + #define POCO_COMPILER_CLANG +#elif defined(_MSC_VER) + #define POCO_COMPILER_MSVC +#elif defined (__GNUC__) + #define POCO_COMPILER_GCC +#elif defined (__MINGW32__) || defined (__MINGW64__) + #define POCO_COMPILER_MINGW +#elif defined (__INTEL_COMPILER) || defined(__ICC) || defined(__ECC) || defined(__ICL) + #define POCO_COMPILER_INTEL +#elif defined (__SUNPRO_CC) + #define POCO_COMPILER_SUN +#elif defined (__MWERKS__) || defined(__CWCC__) + #define POCO_COMPILER_CODEWARRIOR +#elif defined (__sgi) || defined(sgi) + #define POCO_COMPILER_SGI +#elif defined (__HP_aCC) + #define POCO_COMPILER_HP_ACC +#elif defined (__BORLANDC__) || defined(__CODEGEARC__) + #define POCO_COMPILER_CBUILDER +#elif defined (__DMC__) + #define POCO_COMPILER_DMARS +#elif defined (__DECCXX) + #define POCO_COMPILER_COMPAC +#elif (defined (__xlc__) || defined (__xlC__)) && defined(__IBMCPP__) + #define POCO_COMPILER_IBM_XLC // IBM XL C++ +#elif defined (__IBMCPP__) && defined(__COMPILER_VER__) + #define POCO_COMPILER_IBM_XLC_ZOS // IBM z/OS C++ +#endif + + +#ifdef __GNUC__ +#define POCO_UNUSED __attribute__((unused)) +#else +#define POCO_UNUSED +#endif // __GNUC__ + + +#if !defined(POCO_ARCH) + #error "Unknown Hardware Architecture." +#endif + + +#if defined(POCO_OS_FAMILY_WINDOWS) + #define POCO_DEFAULT_NEWLINE_CHARS "\r\n" +#else + #define POCO_DEFAULT_NEWLINE_CHARS "\n" +#endif + + +#endif // Foundation_Platform_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Platform_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/Platform_POSIX.h new file mode 100644 index 0000000000..699735ea2b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Platform_POSIX.h @@ -0,0 +1,53 @@ +// +// Platform_POSIX.h +// +// Library: Foundation +// Package: Core +// Module: Platform +// +// Platform and architecture identification macros +// and platform-specific definitions for various POSIX platforms +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Platform_POSIX_INCLUDED +#define Foundation_Platform_POSIX_INCLUDED + + +// +// PA-RISC based HP-UX platforms have some issues... +// +#if defined(hpux) || defined(_hpux) + #if defined(__hppa) || defined(__hppa__) + #define POCO_NO_SYS_SELECT_H 1 + #if defined(__HP_aCC) + #define POCO_NO_TEMPLATE_ICOMPARE 1 + #endif + #endif +#endif + + +// +// Thread-safety of local static initialization +// +#if __cplusplus >= 201103L || __GNUC__ >= 4 || defined(__clang__) + #ifndef POCO_LOCAL_STATIC_INIT_IS_THREADSAFE + #define POCO_LOCAL_STATIC_INIT_IS_THREADSAFE 1 + #endif +#endif + + +// +// No syslog.h on QNX/BB10 +// +#if defined(__QNXNTO__) + #define POCO_NO_SYSLOGCHANNEL +#endif + + +#endif // Foundation_Platform_POSIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Platform_VX.h b/contrib/libs/poco/Foundation/include/Poco/Platform_VX.h new file mode 100644 index 0000000000..f21e822fdd --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Platform_VX.h @@ -0,0 +1,29 @@ +// +// Platform_VX.h +// +// Library: Foundation +// Package: Core +// Module: Platform +// +// Platform and architecture identification macros +// and platform-specific definitions for VxWorks +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Platform_VX_INCLUDED +#define Foundation_Platform_VX_INCLUDED + + +#define POCO_NO_SYS_SELECT_H +#define POCO_NO_FPENVIRONMENT +#define POCO_NO_WSTRING +#define POCO_NO_SHAREDMEMORY +#define POCO_NO_SYSLOGCHANNEL + + +#endif // Foundation_Platform_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Platform_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/Platform_WIN32.h new file mode 100644 index 0000000000..ab5c791d0c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Platform_WIN32.h @@ -0,0 +1,216 @@ +// +// Platform_WIN32.h +// +// Library: Foundation +// Package: Core +// Module: Platform +// +// Platform and architecture identification macros +// and platform-specific definitions for Windows. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Platform_WIN32_INCLUDED +#define Foundation_Platform_WIN32_INCLUDED + + +#include "Poco/UnWindows.h" + + +#ifndef POCO_FORCE_MIN_WINDOWS_OS_SUPPORT + // Determine the real version. + // This setting can be forced from UnWindows.h + #if defined (_WIN32_WINNT_WINBLUE) + //Windows 8.1 _WIN32_WINNT_WINBLUE (0x0602) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_WINBLUE + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION NTDDI_WINBLUE + #elif defined (_WIN32_WINNT_WIN8) + //Windows 8 _WIN32_WINNT_WIN8 (0x0602) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_WIN8 + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION NTDDI_WIN8 + #elif defined (_WIN32_WINNT_WIN7) + //Windows 7 _WIN32_WINNT_WIN7 (0x0601) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_WIN7 + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION NTDDI_WIN7 + #elif defined (_WIN32_WINNT_WS08) + //Windows Server 2008 _WIN32_WINNT_WS08 (0x0600) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_WS08 + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION NTDDI_WS08 + #elif defined (_WIN32_WINNT_VISTA) + //Windows Vista _WIN32_WINNT_VISTA (0x0600) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_VISTA + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION NTDDI_VISTA + #elif defined (_WIN32_WINNT_LONGHORN) + //Windows Vista and server 2008 Development _WIN32_WINNT_LONGHORN (0x0600) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_LONGHORN + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION 0x06000000 // hardcoded, VS90 can't find NTDDI_* macros + #elif defined (_WIN32_WINNT_WS03) + //Windows Server 2003 with SP1, + //Windows XP with SP2 _WIN32_WINNT_WS03 (0x0502) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_WS03 + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION NTDDI_WS03 + #elif defined (_WIN32_WINNT_WINXP) + //Windows Server 2003, Windows XP _WIN32_WINNT_WINXP (0x0501) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_WINXP + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION NTDDI_WINXP + #elif defined (_WIN32_WINNT_WIN2K) + //Windows 2000 _WIN32_WINNT_WIN2K (0x0500) + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT _WIN32_WINNT_WIN2K + #elif defined (WINVER) + // fail back on WINVER + #ifdef _WIN32_WINNT + #undef _WIN32_WINNT + #endif + #define _WIN32_WINNT WINVER + #elif !defined(_WIN32_WINNT) + // last resort = Win XP, SP2 is minimum supported + #define _WIN32_WINNT 0x0502 + #ifdef NTDDI_VERSION + #undef NTDDI_VERSION + #endif + #define NTDDI_VERSION 0x05020000 + #endif +#endif // POCO_FORCE_MIN_WINDOWS_OS_SUPPORT + + +#if defined(_MSC_VER) && !defined(POCO_MSVC_SECURE_WARNINGS) && !defined(_CRT_SECURE_NO_DEPRECATE) + #define _CRT_SECURE_NO_DEPRECATE +#endif + + +// Verify that we're built with the multithreaded +// versions of the runtime libraries +#if defined(_MSC_VER) && !defined(_MT) + #error Must compile with /MD, /MDd, /MT or /MTd +#endif + + +// Check debug/release settings consistency +#if defined(NDEBUG) && defined(_DEBUG) + #error Inconsistent build settings (check for /MD[d]) +#endif + + +#if (_MSC_VER >= 1300) && (_MSC_VER < 1400) // Visual Studio 2003, MSVC++ 7.1 + #define POCO_MSVS_VERSION 2003 + #define POCO_MSVC_VERSION 71 +#elif (_MSC_VER >= 1400) && (_MSC_VER < 1500) // Visual Studio 2005, MSVC++ 8.0 + #define POCO_MSVS_VERSION 2005 + #define POCO_MSVC_VERSION 80 +#elif (_MSC_VER >= 1500) && (_MSC_VER < 1600) // Visual Studio 2008, MSVC++ 9.0 + #define POCO_MSVS_VERSION 2008 + #define POCO_MSVC_VERSION 90 +#elif (_MSC_VER >= 1600) && (_MSC_VER < 1700) // Visual Studio 2010, MSVC++ 10.0 + #define POCO_MSVS_VERSION 2010 + #define POCO_MSVC_VERSION 100 +#elif (_MSC_VER >= 1700) && (_MSC_VER < 1800) // Visual Studio 2012, MSVC++ 11.0 + #define POCO_MSVS_VERSION 2012 + #define POCO_MSVC_VERSION 110 +#elif (_MSC_VER >= 1800) && (_MSC_VER < 1900) // Visual Studio 2013, MSVC++ 12.0 + #define POCO_MSVS_VERSION 2013 + #define POCO_MSVC_VERSION 120 +#elif (_MSC_VER >= 1900) && (_MSC_VER < 1910) // Visual Studio 2015, MSVC++ 14.0 + #define POCO_MSVS_VERSION 2015 + #define POCO_MSVC_VERSION 140 +#elif (_MSC_VER >= 1910) && (_MSC_VER < 2000) // Visual Studio 2017, MSVC++ 14.1 + #define POCO_MSVS_VERSION 2017 + #define POCO_MSVC_VERSION 141 +#endif + + +// Unicode Support +#if defined(UNICODE) && !defined(POCO_WIN32_UTF8) + #define POCO_WIN32_UTF8 +#endif + + +#if !defined(POCO_WIN32_UTF8) + #pragma message("Compiling POCO on Windows without #define POCO_WIN32_UTF8 is deprecated.") +#endif + + +// Turn off some annoying warnings +#if defined(_MSC_VER) + #pragma warning(disable:4018) // signed/unsigned comparison + #pragma warning(disable:4250) // VC++ 11.0: inheriting from std stream classes produces C4250 warning; + // see <http://connect.microsoft.com/VisualStudio/feedback/details/733720/inheriting-from-std-fstream-produces-c4250-warning> + #pragma warning(disable:4251) // ... needs to have dll-interface warning + #pragma warning(disable:4275) // non dll-interface class 'std::exception' used as base for dll-interface class 'Poco::Exception' + #pragma warning(disable:4344) // behavior change: use of explicit template arguments results in call to '...' but '...' is a better match + #pragma warning(disable:4351) // new behavior: elements of array '...' will be default initialized + #pragma warning(disable:4355) // 'this' : used in base member initializer list + #pragma warning(disable:4675) // resolved overload was found by argument-dependent lookup + #pragma warning(disable:4996) // VC++ 8.0 deprecation warnings +#endif + + +// Enable C++11 support for VS 2010 and newer +#if defined(_MSC_VER) && (_MSC_VER >= 1700) && !defined(POCO_ENABLE_CPP11) + #define POCO_ENABLE_CPP11 +#endif + + +#if defined(__INTEL_COMPILER) + #pragma warning(disable:1738) // base class dllexport/dllimport specification differs from that of the derived class + #pragma warning(disable:1478) // function ... was declared "deprecated" + #pragma warning(disable:1744) // field of class type without a DLL interface used in a class with a DLL interface +#endif + + +#endif // Foundation_Platform_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Poco.h b/contrib/libs/poco/Foundation/include/Poco/Poco.h new file mode 100644 index 0000000000..cc5dd0ee17 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Poco.h @@ -0,0 +1,24 @@ +// +// Poco.h +// +// Library: Foundation +// Package: Core +// Module: Foundation +// +// Basic definitions for the POCO libraries. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Poco_INCLUDED +#define Foundation_Poco_INCLUDED + + +#include "Poco/Foundation.h" + + +#endif // Foundation_Poco_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PriorityDelegate.h b/contrib/libs/poco/Foundation/include/Poco/PriorityDelegate.h new file mode 100644 index 0000000000..7c776b9406 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PriorityDelegate.h @@ -0,0 +1,464 @@ +// +// PriorityDelegate.h +// +// Library: Foundation +// Package: Events +// Module: PriorityDelegate +// +// Implementation of the PriorityDelegate template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PriorityDelegate_INCLUDED +#define Foundation_PriorityDelegate_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractPriorityDelegate.h" +#include "Poco/PriorityExpire.h" +#include "Poco/FunctionPriorityDelegate.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class TObj, class TArgs, bool useSender = true> +class PriorityDelegate: public AbstractPriorityDelegate<TArgs> +{ +public: + typedef void (TObj::*NotifyMethod)(const void*, TArgs&); + + PriorityDelegate(TObj* obj, NotifyMethod method, int prio): + AbstractPriorityDelegate<TArgs>(prio), + _receiverObject(obj), + _receiverMethod(method) + { + } + + PriorityDelegate(const PriorityDelegate& delegate): + AbstractPriorityDelegate<TArgs>(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + PriorityDelegate& operator = (const PriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_pTarget = delegate._pTarget; + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + this->_priority = delegate._priority; + } + return *this; + } + + ~PriorityDelegate() + { + } + + bool notify(const void* sender, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_receiverObject) + { + (_receiverObject->*_receiverMethod)(sender, arguments); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const PriorityDelegate* pOtherDelegate = dynamic_cast<const PriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod; + } + + AbstractDelegate<TArgs>* clone() const + { + return new PriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _receiverObject = 0; + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + Mutex _mutex; + +private: + PriorityDelegate(); +}; + + +template <class TObj, class TArgs> +class PriorityDelegate<TObj, TArgs, false>: public AbstractPriorityDelegate<TArgs> +{ +public: + typedef void (TObj::*NotifyMethod)(TArgs&); + + PriorityDelegate(TObj* obj, NotifyMethod method, int prio): + AbstractPriorityDelegate<TArgs>(prio), + _receiverObject(obj), + _receiverMethod(method) + { + } + + PriorityDelegate(const PriorityDelegate& delegate): + AbstractPriorityDelegate<TArgs>(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + PriorityDelegate& operator = (const PriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_pTarget = delegate._pTarget; + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + this->_priority = delegate._priority; + } + return *this; + } + + ~PriorityDelegate() + { + } + + bool notify(const void* sender, TArgs& arguments) + { + Mutex::ScopedLock lock(_mutex); + if (_receiverObject) + { + (_receiverObject->*_receiverMethod)(arguments); + return true; + } + return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + const PriorityDelegate* pOtherDelegate = dynamic_cast<const PriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod; + } + + AbstractDelegate<TArgs>* clone() const + { + return new PriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _receiverObject = 0; + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + Mutex _mutex; + +private: + PriorityDelegate(); +}; + + +template <class TObj> +class PriorityDelegate<TObj, void, true>: public AbstractPriorityDelegate<void> +{ +public: + typedef void (TObj::*NotifyMethod)(const void*); + + PriorityDelegate(TObj* obj, NotifyMethod method, int prio): + AbstractPriorityDelegate<void>(prio), + _receiverObject(obj), + _receiverMethod(method) + { + } + + PriorityDelegate(const PriorityDelegate& delegate): + AbstractPriorityDelegate<void>(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + PriorityDelegate& operator = (const PriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_pTarget = delegate._pTarget; + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + this->_priority = delegate._priority; + } + return *this; + } + + ~PriorityDelegate() + { + } + + bool notify(const void* sender) + { + Mutex::ScopedLock lock(_mutex); + if (_receiverObject) + { + (_receiverObject->*_receiverMethod)(sender); + return true; + } + else return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const PriorityDelegate* pOtherDelegate = dynamic_cast<const PriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod; + } + + AbstractDelegate<void>* clone() const + { + return new PriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _receiverObject = 0; + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + Mutex _mutex; + +private: + PriorityDelegate(); +}; + + +template <class TObj> +class PriorityDelegate<TObj, void, false>: public AbstractPriorityDelegate<void> +{ +public: + typedef void (TObj::*NotifyMethod)(); + + PriorityDelegate(TObj* obj, NotifyMethod method, int prio): + AbstractPriorityDelegate<void>(prio), + _receiverObject(obj), + _receiverMethod(method) + { + } + + PriorityDelegate(const PriorityDelegate& delegate): + AbstractPriorityDelegate<void>(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + PriorityDelegate& operator = (const PriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_pTarget = delegate._pTarget; + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + this->_priority = delegate._priority; + } + return *this; + } + + ~PriorityDelegate() + { + } + + bool notify(const void* sender) + { + Mutex::ScopedLock lock(_mutex); + if (_receiverObject) + { + (_receiverObject->*_receiverMethod)(); + return true; + } + return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + const PriorityDelegate* pOtherDelegate = dynamic_cast<const PriorityDelegate*>(other.unwrap()); + return pOtherDelegate && this->priority() == pOtherDelegate->priority() && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod; + } + + AbstractDelegate<void>* clone() const + { + return new PriorityDelegate(*this); + } + + void disable() + { + Mutex::ScopedLock lock(_mutex); + _receiverObject = 0; + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + Mutex _mutex; + +private: + PriorityDelegate(); +}; + + +template <class TObj, class TArgs> +static PriorityDelegate<TObj, TArgs, true> priorityDelegate(TObj* pObj, void (TObj::*NotifyMethod)(const void*, TArgs&), int prio) +{ + return PriorityDelegate<TObj, TArgs, true>(pObj, NotifyMethod, prio); +} + + +template <class TObj, class TArgs> +static PriorityDelegate<TObj, TArgs, false> priorityDelegate(TObj* pObj, void (TObj::*NotifyMethod)(TArgs&), int prio) +{ + return PriorityDelegate<TObj, TArgs, false>(pObj, NotifyMethod, prio); +} + + +template <class TObj, class TArgs> +static PriorityExpire<TArgs> priorityDelegate(TObj* pObj, void (TObj::*NotifyMethod)(const void*, TArgs&), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<TArgs>(PriorityDelegate<TObj, TArgs, true>(pObj, NotifyMethod, prio), expireMilliSec); +} + + +template <class TObj, class TArgs> +static PriorityExpire<TArgs> priorityDelegate(TObj* pObj, void (TObj::*NotifyMethod)(TArgs&), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<TArgs>(PriorityDelegate<TObj, TArgs, false>(pObj, NotifyMethod, prio), expireMilliSec); +} + + +template <class TArgs> +static PriorityExpire<TArgs> priorityDelegate(void (*NotifyMethod)(const void*, TArgs&), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<TArgs>(FunctionPriorityDelegate<TArgs, true, true>(NotifyMethod, prio), expireMilliSec); +} + + +template <class TArgs> +static PriorityExpire<TArgs> priorityDelegate(void (*NotifyMethod)(void*, TArgs&), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<TArgs>(FunctionPriorityDelegate<TArgs, true, false>(NotifyMethod, prio), expireMilliSec); +} + + +template <class TArgs> +static PriorityExpire<TArgs> priorityDelegate(void (*NotifyMethod)(TArgs&), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<TArgs>(FunctionPriorityDelegate<TArgs, false>(NotifyMethod, prio), expireMilliSec); +} + + +template <class TArgs> +static FunctionPriorityDelegate<TArgs, true, true> priorityDelegate(void (*NotifyMethod)(const void*, TArgs&), int prio) +{ + return FunctionPriorityDelegate<TArgs, true, true>(NotifyMethod, prio); +} + + +template <class TArgs> +static FunctionPriorityDelegate<TArgs, true, false> priorityDelegate(void (*NotifyMethod)(void*, TArgs&), int prio) +{ + return FunctionPriorityDelegate<TArgs, true, false>(NotifyMethod, prio); +} + + +template <class TArgs> +static FunctionPriorityDelegate<TArgs, false> priorityDelegate(void (*NotifyMethod)(TArgs&), int prio) +{ + return FunctionPriorityDelegate<TArgs, false>(NotifyMethod, prio); +} + + +template <class TObj> +static PriorityDelegate<TObj, void, true> priorityDelegate(TObj* pObj, void (TObj::*NotifyMethod)(const void*), int prio) +{ + return PriorityDelegate<TObj, void, true>(pObj, NotifyMethod, prio); +} + + +template <class TObj> +static PriorityDelegate<TObj, void, false> priorityDelegate(TObj* pObj, void (TObj::*NotifyMethod)(), int prio) +{ + return PriorityDelegate<TObj, void, false>(pObj, NotifyMethod, prio); +} + + +template <class TObj> +static PriorityExpire<void> priorityDelegate(TObj* pObj, void (TObj::*NotifyMethod)(const void*), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<void>(PriorityDelegate<TObj, void, true>(pObj, NotifyMethod, prio), expireMilliSec); +} + + +template <class TObj> +static PriorityExpire<void> priorityDelegate(TObj* pObj, void (TObj::*NotifyMethod)(), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<void>(PriorityDelegate<TObj, void, false>(pObj, NotifyMethod, prio), expireMilliSec); +} + + +inline PriorityExpire<void> priorityDelegate(void (*NotifyMethod)(const void*), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<void>(FunctionPriorityDelegate<void, true, true>(NotifyMethod, prio), expireMilliSec); +} + + +inline PriorityExpire<void> priorityDelegate(void (*NotifyMethod)(void*), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<void>(FunctionPriorityDelegate<void, true, false>(NotifyMethod, prio), expireMilliSec); +} + + +inline PriorityExpire<void> priorityDelegate(void (*NotifyMethod)(), int prio, Timestamp::TimeDiff expireMilliSec) +{ + return PriorityExpire<void>(FunctionPriorityDelegate<void, false>(NotifyMethod, prio), expireMilliSec); +} + + +inline FunctionPriorityDelegate<void, true, true> priorityDelegate(void (*NotifyMethod)(const void*), int prio) +{ + return FunctionPriorityDelegate<void, true, true>(NotifyMethod, prio); +} + + +inline FunctionPriorityDelegate<void, true, false> priorityDelegate(void (*NotifyMethod)(void*), int prio) +{ + return FunctionPriorityDelegate<void, true, false>(NotifyMethod, prio); +} + + +inline FunctionPriorityDelegate<void, false> priorityDelegate(void (*NotifyMethod)(), int prio) +{ + return FunctionPriorityDelegate<void, false>(NotifyMethod, prio); +} + + +} // namespace Poco + + +#endif // Foundation_PriorityDelegate_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PriorityEvent.h b/contrib/libs/poco/Foundation/include/Poco/PriorityEvent.h new file mode 100644 index 0000000000..48b9f604f6 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PriorityEvent.h @@ -0,0 +1,61 @@ +// +// PriorityEvent.h +// +// Library: Foundation +// Package: Events +// Module: PriorityEvent +// +// Implementation of the PriorityEvent template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PriorityEvent_INCLUDED +#define Foundation_PriorityEvent_INCLUDED + + +#include "Poco/AbstractEvent.h" +#include "Poco/PriorityStrategy.h" +#include "Poco/AbstractPriorityDelegate.h" + + +namespace Poco { + + +template <class TArgs, class TMutex = FastMutex> +class PriorityEvent: public AbstractEvent < + TArgs, + PriorityStrategy<TArgs, AbstractPriorityDelegate<TArgs> >, + AbstractPriorityDelegate<TArgs>, + TMutex +> + /// A PriorityEvent uses internally a PriorityStrategy which + /// invokes delegates in order of priority (lower priorities first). + /// PriorityEvent's can only be used together with PriorityDelegate's. + /// PriorityDelegate's are sorted according to the priority value, when + /// two delegates have the same priority, they are invoked in + /// an arbitrary manner. +{ +public: + PriorityEvent() + { + } + + ~PriorityEvent() + { + } + +private: + PriorityEvent(const PriorityEvent&); + PriorityEvent& operator = (const PriorityEvent&); +}; + + +} // namespace Poco + + +#endif // Foundation_PriorityEvent_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PriorityExpire.h b/contrib/libs/poco/Foundation/include/Poco/PriorityExpire.h new file mode 100644 index 0000000000..9491445f07 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PriorityExpire.h @@ -0,0 +1,195 @@ +// +// PriorityExpire.h +// +// Library: Foundation +// Package: Events +// Module: PriorityExpire +// +// Implementation of the PriorityExpire template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PriorityExpire_INCLUDED +#define Foundation_PriorityExpire_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include "Poco/AbstractPriorityDelegate.h" + + +namespace Poco { + + +template <class TArgs> +class PriorityExpire: public AbstractPriorityDelegate<TArgs> + /// Decorator for AbstractPriorityDelegate adding automatic + /// expiring of registrations to AbstractPriorityDelegate. +{ +public: + PriorityExpire(const AbstractPriorityDelegate<TArgs>& p, Timestamp::TimeDiff expireMilliSec): + AbstractPriorityDelegate<TArgs>(p), + _pDelegate(static_cast<AbstractPriorityDelegate<TArgs>*>(p.clone())), + _expire(expireMilliSec*1000) + { + } + + PriorityExpire(const PriorityExpire& expire): + AbstractPriorityDelegate<TArgs>(expire), + _pDelegate(static_cast<AbstractPriorityDelegate<TArgs>*>(expire._pDelegate->clone())), + _expire(expire._expire), + _creationTime(expire._creationTime) + { + } + + ~PriorityExpire() + { + delete _pDelegate; + } + + PriorityExpire& operator = (const PriorityExpire& expire) + { + if (&expire != this) + { + delete this->_pDelegate; + this->_pTarget = expire._pTarget; + this->_pDelegate = expire._pDelegate->clone(); + this->_expire = expire._expire; + this->_creationTime = expire._creationTime; + } + return *this; + } + + bool notify(const void* sender, TArgs& arguments) + { + if (!expired()) + return this->_pDelegate->notify(sender, arguments); + else + return false; + } + + bool equals(const AbstractDelegate<TArgs>& other) const + { + return other.equals(*_pDelegate); + } + + AbstractPriorityDelegate<TArgs>* clone() const + { + return new PriorityExpire(*this); + } + + void disable() + { + _pDelegate->disable(); + } + + const AbstractPriorityDelegate<TArgs>* unwrap() const + { + return this->_pDelegate; + } + +protected: + bool expired() const + { + return _creationTime.isElapsed(_expire); + } + + AbstractPriorityDelegate<TArgs>* _pDelegate; + Timestamp::TimeDiff _expire; + Timestamp _creationTime; + +private: + PriorityExpire(); +}; + + +template <> +class PriorityExpire<void>: public AbstractPriorityDelegate<void> + /// Decorator for AbstractPriorityDelegate adding automatic + /// expiring of registrations to AbstractPriorityDelegate. +{ +public: + PriorityExpire(const AbstractPriorityDelegate<void>& p, Timestamp::TimeDiff expireMilliSec): + AbstractPriorityDelegate<void>(p), + _pDelegate(static_cast<AbstractPriorityDelegate<void>*>(p.clone())), + _expire(expireMilliSec*1000) + { + } + + PriorityExpire(const PriorityExpire& expire): + AbstractPriorityDelegate<void>(expire), + _pDelegate(static_cast<AbstractPriorityDelegate<void>*>(expire._pDelegate->clone())), + _expire(expire._expire), + _creationTime(expire._creationTime) + { + } + + ~PriorityExpire() + { + delete _pDelegate; + } + + PriorityExpire& operator = (const PriorityExpire& expire) + { + if (&expire != this) + { + delete this->_pDelegate; + this->_pDelegate = static_cast<AbstractPriorityDelegate<void>*>(expire._pDelegate->clone()); + this->_expire = expire._expire; + this->_creationTime = expire._creationTime; + } + return *this; + } + + bool notify(const void* sender) + { + if (!expired()) + return this->_pDelegate->notify(sender); + else + return false; + } + + bool equals(const AbstractDelegate<void>& other) const + { + return other.equals(*_pDelegate); + } + + AbstractPriorityDelegate<void>* clone() const + { + return new PriorityExpire(*this); + } + + void disable() + { + _pDelegate->disable(); + } + + const AbstractPriorityDelegate<void>* unwrap() const + { + return this->_pDelegate; + } + +protected: + bool expired() const + { + return _creationTime.isElapsed(_expire); + } + + AbstractPriorityDelegate<void>* _pDelegate; + Timestamp::TimeDiff _expire; + Timestamp _creationTime; + +private: + PriorityExpire(); +}; + + +} // namespace Poco + + +#endif // Foundation_PriorityExpire_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PriorityNotificationQueue.h b/contrib/libs/poco/Foundation/include/Poco/PriorityNotificationQueue.h new file mode 100644 index 0000000000..e5269ab854 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PriorityNotificationQueue.h @@ -0,0 +1,158 @@ +// +// PriorityNotificationQueue.h +// +// Library: Foundation +// Package: Notifications +// Module: PriorityNotificationQueue +// +// Definition of the PriorityNotificationQueue class. +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PriorityNotificationQueue_INCLUDED +#define Foundation_PriorityNotificationQueue_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Notification.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" +#include <map> +#include <deque> + + +namespace Poco { + + +class NotificationCenter; + + +class Foundation_API PriorityNotificationQueue + /// A PriorityNotificationQueue object provides a way to implement asynchronous + /// notifications. This is especially useful for sending notifications + /// from one thread to another, for example from a background thread to + /// the main (user interface) thread. + /// + /// The PriorityNotificationQueue is quite similar to the NotificationQueue class. + /// The only difference to NotificationQueue is that each Notification is tagged + /// with a priority value. When inserting a Notification into the queue, the + /// Notification is inserted according to the given priority value, with + /// lower priority values being inserted before higher priority + /// values. Therefore, the lower the numerical priority value, the higher + /// the actual notification priority. + /// + /// Notifications are dequeued in order of their priority. + /// + /// The PriorityNotificationQueue can also be used to distribute work from + /// a controlling thread to one or more worker threads. Each worker thread + /// repeatedly calls waitDequeueNotification() and processes the + /// returned notification. Special care must be taken when shutting + /// down a queue with worker threads waiting for notifications. + /// The recommended sequence to shut down and destroy the queue is to + /// 1. set a termination flag for every worker thread + /// 2. call the wakeUpAll() method + /// 3. join each worker thread + /// 4. destroy the notification queue. +{ +public: + PriorityNotificationQueue(); + /// Creates the PriorityNotificationQueue. + + ~PriorityNotificationQueue(); + /// Destroys the PriorityNotificationQueue. + + void enqueueNotification(Notification::Ptr pNotification, int priority); + /// Enqueues the given notification by adding it to + /// the queue according to the given priority. + /// Lower priority values are inserted before higher priority values. + /// The queue takes ownership of the notification, thus + /// a call like + /// notificationQueue.enqueueNotification(new MyNotification, 1); + /// does not result in a memory leak. + + Notification* dequeueNotification(); + /// Dequeues the next pending notification. + /// Returns 0 (null) if no notification is available. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + Notification* waitDequeueNotification(); + /// Dequeues the next pending notification. + /// If no notification is available, waits for a notification + /// to be enqueued. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// This method returns 0 (null) if wakeUpAll() + /// has been called by another thread. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + Notification* waitDequeueNotification(long milliseconds); + /// Dequeues the next pending notification. + /// If no notification is available, waits for a notification + /// to be enqueued up to the specified time. + /// Returns 0 (null) if no notification is available. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + void dispatch(NotificationCenter& notificationCenter); + /// Dispatches all queued notifications to the given + /// notification center. + + void wakeUpAll(); + /// Wakes up all threads that wait for a notification. + + bool empty() const; + /// Returns true iff the queue is empty. + + int size() const; + /// Returns the number of notifications in the queue. + + void clear(); + /// Removes all notifications from the queue. + + bool hasIdleThreads() const; + /// Returns true if the queue has at least one thread waiting + /// for a notification. + + static PriorityNotificationQueue& defaultQueue(); + /// Returns a reference to the default + /// PriorityNotificationQueue. + +protected: + Notification::Ptr dequeueOne(); + +private: + typedef std::multimap<int, Notification::Ptr> NfQueue; + struct WaitInfo + { + Notification::Ptr pNf; + Event nfAvailable; + }; + typedef std::deque<WaitInfo*> WaitQueue; + + NfQueue _nfQueue; + WaitQueue _waitQueue; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_PriorityNotificationQueue_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PriorityStrategy.h b/contrib/libs/poco/Foundation/include/Poco/PriorityStrategy.h new file mode 100644 index 0000000000..65d67a4491 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PriorityStrategy.h @@ -0,0 +1,230 @@ +// +// PriorityStrategy.h +// +// Library: Foundation +// Package: Events +// Module: PrioritytStrategy +// +// Implementation of the DefaultStrategy template. +// +// Copyright (c) 2006-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PriorityStrategy_INCLUDED +#define Foundation_PriorityStrategy_INCLUDED + + +#include "Poco/NotificationStrategy.h" +#include "Poco/SharedPtr.h" +#include <vector> + + +namespace Poco { + + +template <class TArgs, class TDelegate> +class PriorityStrategy: public NotificationStrategy<TArgs, TDelegate> + /// NotificationStrategy for PriorityEvent. + /// + /// Delegates are kept in a std::vector<>, ordered + /// by their priority. +{ +public: + typedef TDelegate* DelegateHandle; + typedef SharedPtr<TDelegate> DelegatePtr; + typedef std::vector<DelegatePtr> Delegates; + typedef typename Delegates::iterator Iterator; + +public: + PriorityStrategy() + { + } + + PriorityStrategy(const PriorityStrategy& s): + _delegates(s._delegates) + { + } + + ~PriorityStrategy() + { + } + + void notify(const void* sender, TArgs& arguments) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + (*it)->notify(sender, arguments); + } + } + + DelegateHandle add(const TDelegate& delegate) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if ((*it)->priority() > delegate.priority()) + { + DelegatePtr pDelegate(static_cast<TDelegate*>(delegate.clone())); + _delegates.insert(it, pDelegate); + return pDelegate.get(); + } + } + DelegatePtr pDelegate(static_cast<TDelegate*>(delegate.clone())); + _delegates.push_back(pDelegate); + return pDelegate.get(); + } + + void remove(const TDelegate& delegate) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if (delegate.equals(**it)) + { + (*it)->disable(); + _delegates.erase(it); + return; + } + } + } + + void remove(DelegateHandle delegateHandle) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if (*it == delegateHandle) + { + (*it)->disable(); + _delegates.erase(it); + return; + } + } + } + + PriorityStrategy& operator = (const PriorityStrategy& s) + { + if (this != &s) + { + _delegates = s._delegates; + } + return *this; + } + + void clear() + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + (*it)->disable(); + } + _delegates.clear(); + } + + bool empty() const + { + return _delegates.empty(); + } + +protected: + Delegates _delegates; +}; + + +template <class TDelegate> +class PriorityStrategy<void, TDelegate> + /// NotificationStrategy for PriorityEvent. + /// + /// Delegates are kept in a std::vector<>, ordered + /// by their priority. +{ +public: + typedef TDelegate* DelegateHandle; + typedef SharedPtr<TDelegate> DelegatePtr; + typedef std::vector<DelegatePtr> Delegates; + typedef typename Delegates::iterator Iterator; + +public: + + void notify(const void* sender) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + (*it)->notify(sender); + } + } + + DelegateHandle add(const TDelegate& delegate) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if ((*it)->priority() > delegate.priority()) + { + DelegatePtr pDelegate(static_cast<TDelegate*>(delegate.clone())); + _delegates.insert(it, pDelegate); + return pDelegate.get(); + } + } + DelegatePtr pDelegate(static_cast<TDelegate*>(delegate.clone())); + _delegates.push_back(pDelegate); + return pDelegate.get(); + } + + void remove(const TDelegate& delegate) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if (delegate.equals(**it)) + { + (*it)->disable(); + _delegates.erase(it); + return; + } + } + } + + void remove(DelegateHandle delegateHandle) + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + if (*it == delegateHandle) + { + (*it)->disable(); + _delegates.erase(it); + return; + } + } + } + + PriorityStrategy& operator = (const PriorityStrategy& s) + { + if (this != &s) + { + _delegates = s._delegates; + } + return *this; + } + + void clear() + { + for (Iterator it = _delegates.begin(); it != _delegates.end(); ++it) + { + (*it)->disable(); + } + _delegates.clear(); + } + + bool empty() const + { + return _delegates.empty(); + } + +protected: + Delegates _delegates; +}; + + +} // namespace Poco + + +#endif // Foundation_PriorityStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Process.h b/contrib/libs/poco/Foundation/include/Poco/Process.h new file mode 100644 index 0000000000..f9fefc524b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Process.h @@ -0,0 +1,266 @@ +// +// Process.h +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the Process class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Process_INCLUDED +#define Foundation_Process_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#if defined(_WIN32_WCE) +#include "Process_WINCE.h" +#else +#include "Poco/Process_WIN32U.h" +#endif +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/Process_WIN32.h" +#elif defined(POCO_VXWORKS) +#include "Poco/Process_VX.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/Process_UNIX.h" +#endif + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandle + /// A handle for a process created with Process::launch(). + /// + /// This handle can be used to determine the process ID of + /// the newly created process and it can be used to wait for + /// the completion of a process. +{ +public: + typedef ProcessImpl::PIDImpl PID; + + ProcessHandle(const ProcessHandle& handle); + /// Creates a ProcessHandle by copying another one. + + ~ProcessHandle(); + /// Destroys the ProcessHandle. + + ProcessHandle& operator = (const ProcessHandle& handle); + /// Assigns another handle. + + PID id() const; + /// Returns the process ID. + + int wait() const; + /// Waits for the process to terminate + /// and returns the exit code of the process. + +protected: + ProcessHandle(ProcessHandleImpl* pImpl); + +private: + ProcessHandle(); + + ProcessHandleImpl* _pImpl; + + friend class Process; +}; + + +class Foundation_API Process: public ProcessImpl + /// This class provides methods for working with processes. +{ +public: + typedef PIDImpl PID; + typedef ArgsImpl Args; + typedef EnvImpl Env; + + static PID id(); + /// Returns the process ID of the current process. + + static void times(long& userTime, long& kernelTime); + /// Returns the number of seconds spent by the + /// current process in user and kernel mode. + + static ProcessHandle launch(const std::string& command, const Args& args); + /// Creates a new process for the given command and returns + /// a ProcessHandle of the new process. The given arguments are + /// passed to the command on the command line. + + static ProcessHandle launch( + const std::string& command, + const Args& args, + const std::string& initialDirectory); + /// Creates a new process for the given command and returns + /// a ProcessHandle of the new process. The given arguments are + /// passed to the command on the command line. + /// The process starts executing in the specified initial directory. + + static ProcessHandle launch( + const std::string& command, + const Args& args, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe); + /// Creates a new process for the given command and returns + /// a ProcessHandle of the new process. The given arguments are + /// passed to the command on the command line. + /// + /// If inPipe, outPipe or errPipe is non-null, the corresponding + /// standard input, standard output or standard error stream + /// of the launched process is redirected to the Pipe. + /// PipeInputStream or PipeOutputStream can be used to + /// send receive data from, or send data to the process. + /// + /// Note: the same Pipe can be used for both outPipe and errPipe. + /// + /// After a Pipe has been passed as inPipe, only write operations + /// are valid. After a Pipe has been passed as outPipe or errPipe, + /// only read operations are valid. + /// + /// It is forbidden to pass the same pipe as inPipe and outPipe or errPipe. + /// + /// Usage example: + /// Pipe outPipe; + /// Process::Args args; + /// ProcessHandle ph(launch("/bin/ps", args, 0, &outPipe, 0)); + /// PipeInputStream istr(outPipe); + /// ... // read output of ps from istr + /// int rc = ph.wait(); + + static ProcessHandle launch( + const std::string& command, + const Args& args, + const std::string& initialDirectory, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe); + /// Creates a new process for the given command and returns + /// a ProcessHandle of the new process. The given arguments are + /// passed to the command on the command line. + /// The process starts executing in the specified initial directory. + /// + /// If inPipe, outPipe or errPipe is non-null, the corresponding + /// standard input, standard output or standard error stream + /// of the launched process is redirected to the Pipe. + /// PipeInputStream or PipeOutputStream can be used to + /// send receive data from, or send data to the process. + /// + /// Note: the same Pipe can be used for both outPipe and errPipe. + /// + /// After a Pipe has been passed as inPipe, only write operations + /// are valid. After a Pipe has been passed as outPipe or errPipe, + /// only read operations are valid. + /// + /// It is forbidden to pass the same pipe as inPipe and outPipe or errPipe. + /// + /// Usage example: + /// Pipe outPipe; + /// Process::Args args; + /// ProcessHandle ph(launch("/bin/ps", args, 0, &outPipe, 0)); + /// PipeInputStream istr(outPipe); + /// ... // read output of ps from istr + /// int rc = ph.wait(); + + static ProcessHandle launch( + const std::string& command, + const Args& args, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe, + const Env& env); + /// Creates a new process for the given command and returns + /// a ProcessHandle of the new process. The given arguments are + /// passed to the command on the command line. + /// + /// If inPipe, outPipe or errPipe is non-null, the corresponding + /// standard input, standard output or standard error stream + /// of the launched process is redirected to the Pipe. + /// + /// The launched process is given the specified environment variables. + + static ProcessHandle launch( + const std::string& command, + const Args& args, + const std::string& initialDirectory, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe, + const Env& env); + /// Creates a new process for the given command and returns + /// a ProcessHandle of the new process. The given arguments are + /// passed to the command on the command line. + /// The process starts executing in the specified initial directory. + /// If inPipe, outPipe or errPipe is non-null, the corresponding + /// standard input, standard output or standard error stream + /// of the launched process is redirected to the Pipe. + /// The launched process is given the specified environment variables. + + static int wait(const ProcessHandle& handle); + /// Waits for the process specified by handle to terminate + /// and returns the exit code of the process. + + static bool isRunning(const ProcessHandle& handle); + /// check if the process specified by handle is running or not + /// + /// This is preferable on Windows where process IDs + /// may be reused. + + static bool isRunning(PID pid); + /// Check if the process specified by given pid is running or not. + + static void kill(ProcessHandle& handle); + /// Kills the process specified by handle. + /// + /// This is preferable on Windows where process IDs + /// may be reused. + + static void kill(PID pid); + /// Kills the process with the given pid. + + static void requestTermination(PID pid); + /// Requests termination of the process with the give PID. + /// + /// On Unix platforms, this will send a SIGINT to the + /// process and thus work with arbitrary processes. + /// + /// On other platforms, a global event flag + /// will be set. Setting the flag will cause + /// Util::ServerApplication::waitForTerminationRequest() to + /// return. Therefore this will only work with applications + /// based on Util::ServerApplication. +}; + + +// +// inlines +// +inline Process::PID Process::id() +{ + return ProcessImpl::idImpl(); +} + + +inline void Process::times(long& userTime, long& kernelTime) +{ + ProcessImpl::timesImpl(userTime, kernelTime); +} + + +} // namespace Poco + + +#endif // Foundation_Process_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Process_UNIX.h b/contrib/libs/poco/Foundation/include/Poco/Process_UNIX.h new file mode 100644 index 0000000000..b33dd08210 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Process_UNIX.h @@ -0,0 +1,86 @@ +// +// Process_UNIX.h +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Process_UNIX_INCLUDED +#define Foundation_Process_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include <unistd.h> +#include <vector> +#include <map> + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(pid_t pid); + ~ProcessHandleImpl(); + + pid_t id() const; + int wait() const; + +private: + pid_t _pid; +}; + + +class Foundation_API ProcessImpl +{ +public: + typedef pid_t PIDImpl; + typedef std::vector<std::string> ArgsImpl; + typedef std::map<std::string, std::string> EnvImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl( + const std::string& command, + const ArgsImpl& args, + const std::string& initialDirectory, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe, + const EnvImpl& env); + static void killImpl(ProcessHandleImpl& handle); + static void killImpl(PIDImpl pid); + static bool isRunningImpl(const ProcessHandleImpl& handle); + static bool isRunningImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); + +private: + static ProcessHandleImpl* launchByForkExecImpl( + const std::string& command, + const ArgsImpl& args, + const std::string& initialDirectory, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe, + const EnvImpl& env); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Process_VX.h b/contrib/libs/poco/Foundation/include/Poco/Process_VX.h new file mode 100644 index 0000000000..0ac9bcef23 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Process_VX.h @@ -0,0 +1,78 @@ +// +// Process_VX.h +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for VxWorks. +// +// Copyright (c) 2004-20011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Process_VX_INCLUDED +#define Foundation_Process_VX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include <vector> +#include <map> + + +#undef PID + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(int pid); + ~ProcessHandleImpl(); + + int id() const; + int wait() const; + +private: + int _pid; +}; + + +class Foundation_API ProcessImpl +{ +public: + typedef int PIDImpl; + typedef std::vector<std::string> ArgsImpl; + typedef std::map<std::string, std::string> EnvImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl( + const std::string& command, + const ArgsImpl& args, + const std::string& initialDirectory, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe, + const EnvImpl& env); + static void killImpl(ProcessHandleImpl& handle); + static void killImpl(PIDImpl pid); + static bool isRunningImpl(const ProcessHandleImpl& handle); + static bool isRunningImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Process_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/Process_WIN32.h new file mode 100644 index 0000000000..afed42c25a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Process_WIN32.h @@ -0,0 +1,83 @@ +// +// Process_WIN32.h +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Process_WIN32_INCLUDED +#define Foundation_Process_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include <vector> +#include <map> +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(HANDLE _hProcess, UInt32 pid); + ~ProcessHandleImpl(); + + UInt32 id() const; + HANDLE process() const; + int wait() const; + void closeHandle(); + +private: + HANDLE _hProcess; + UInt32 _pid; + + ProcessHandleImpl(const ProcessHandleImpl&); + ProcessHandleImpl& operator = (const ProcessHandleImpl&); +}; + + +class Foundation_API ProcessImpl +{ +public: + typedef UInt32 PIDImpl; + typedef std::vector<std::string> ArgsImpl; + typedef std::map<std::string, std::string> EnvImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl( + const std::string& command, + const ArgsImpl& args, + const std::string& initialDirectory, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe, + const EnvImpl& env); + static void killImpl(ProcessHandleImpl& handle); + static void killImpl(PIDImpl pid); + static bool isRunningImpl(const ProcessHandleImpl& handle); + static bool isRunningImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); + static std::string terminationEventName(PIDImpl pid); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Process_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/Process_WIN32U.h new file mode 100644 index 0000000000..bb52013607 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Process_WIN32U.h @@ -0,0 +1,83 @@ +// +// Process_WIN32U.h +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Process_WIN32U_INCLUDED +#define Foundation_Process_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include <vector> +#include <map> +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(HANDLE _hProcess, UInt32 pid); + ~ProcessHandleImpl(); + + UInt32 id() const; + HANDLE process() const; + int wait() const; + void closeHandle(); + +private: + HANDLE _hProcess; + UInt32 _pid; + + ProcessHandleImpl(const ProcessHandleImpl&); + ProcessHandleImpl& operator = (const ProcessHandleImpl&); +}; + + +class Foundation_API ProcessImpl +{ +public: + typedef UInt32 PIDImpl; + typedef std::vector<std::string> ArgsImpl; + typedef std::map<std::string, std::string> EnvImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl( + const std::string& command, + const ArgsImpl& args, + const std::string& initialDirectory, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe, + const EnvImpl& env); + static void killImpl(ProcessHandleImpl& handle); + static void killImpl(PIDImpl pid); + static bool isRunningImpl(const ProcessHandleImpl& handle); + static bool isRunningImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); + static std::string terminationEventName(PIDImpl pid); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Process_WINCE.h b/contrib/libs/poco/Foundation/include/Poco/Process_WINCE.h new file mode 100644 index 0000000000..f754c577ab --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Process_WINCE.h @@ -0,0 +1,83 @@ +// +// Process_WINCE.h +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for WIN32. +// +// Copyright (c) 2004-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Process_WINCE_INCLUDED +#define Foundation_Process_WINCE_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include <vector> +#include <map> +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(HANDLE _hProcess, UInt32 pid); + ~ProcessHandleImpl(); + + UInt32 id() const; + HANDLE process() const; + int wait() const; + void closeHandle(); + +private: + HANDLE _hProcess; + UInt32 _pid; + + ProcessHandleImpl(const ProcessHandleImpl&); + ProcessHandleImpl& operator = (const ProcessHandleImpl&); +}; + + +class Foundation_API ProcessImpl +{ +public: + typedef UInt32 PIDImpl; + typedef std::vector<std::string> ArgsImpl; + typedef std::map<std::string, std::string> EnvImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl( + const std::string& command, + const ArgsImpl& args, + const std::string& initialDirectory, + Pipe* inPipe, + Pipe* outPipe, + Pipe* errPipe, + const EnvImpl& env); + static void killImpl(ProcessHandleImpl& handle); + static void killImpl(PIDImpl pid); + static bool isRunningImpl(const ProcessHandleImpl& handle); + static bool isRunningImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); + static std::string terminationEventName(PIDImpl pid); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_WINCE_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/PurgeStrategy.h b/contrib/libs/poco/Foundation/include/Poco/PurgeStrategy.h new file mode 100644 index 0000000000..79ca2bde41 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/PurgeStrategy.h @@ -0,0 +1,107 @@ +// +// PurgeStrategy.h +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Definition of the PurgeStrategy class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_PurgeStrategy_INCLUDED +#define Foundation_PurgeStrategy_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/File.h" +#include "Poco/Timespan.h" +#include <vector> + + +namespace Poco { + + +class Foundation_API PurgeStrategy + /// The PurgeStrategy is used by FileChannel + /// to purge archived log files. +{ +public: + PurgeStrategy(); + virtual ~PurgeStrategy(); + + virtual void purge(const std::string& path) = 0; + /// Purges archived log files. The path to the + /// current "hot" log file is given. + /// To find archived log files, look for files + /// with a name consisting of the given path + /// plus any suffix (e.g., .1, .20050929081500, .1.gz). + /// A list of archived files can be obtained by calling + /// the list() method. + +protected: + void list(const std::string& path, std::vector<File>& files); + /// Fills the given vector with a list of archived log + /// files. The path of the current "hot" log file is + /// given in path. + /// + /// All files with the same name as the one given in path, + /// plus some suffix (e.g., .1, .20050929081500, .1.gz) are + /// considered archived files. + +private: + PurgeStrategy(const PurgeStrategy&); + PurgeStrategy& operator = (const PurgeStrategy&); +}; + + +class Foundation_API PurgeByAgeStrategy: public PurgeStrategy + /// This purge strategy purges all files that have + /// exceeded a given age (given in seconds). +{ +public: + PurgeByAgeStrategy(const Timespan& age); + ~PurgeByAgeStrategy(); + + void purge(const std::string& path); + +private: + Timespan _age; +}; + + +class Foundation_API PurgeByCountStrategy: public PurgeStrategy + /// This purge strategy ensures that a maximum number + /// of archived files is not exceeded. Files are deleted + /// based on their age, with oldest files deleted first. +{ +public: + PurgeByCountStrategy(int count); + ~PurgeByCountStrategy(); + + void purge(const std::string& path); + +private: + int _count; +}; + + +class Foundation_API PurgeOneFileStrategy: public PurgeStrategy + /// This purge strategy unconditionally purges one oldest file. + /// If there are no archived files, it will truncate current "hot" log file. + /// Intended usage: when there are no space left on device with logs. +{ +public: + void purge(const std::string& path); +}; + + +} // namespace Poco + + +#endif // Foundation_PurgeStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RWLock.h b/contrib/libs/poco/Foundation/include/Poco/RWLock.h new file mode 100644 index 0000000000..23b3b16cb2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RWLock.h @@ -0,0 +1,203 @@ +// +// RWLock.h +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLock class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RWLock_INCLUDED +#define Foundation_RWLock_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#if defined(_WIN32_WCE) +#include "Poco/RWLock_WINCE.h" +#else +#include "Poco/RWLock_WIN32.h" +#endif +#elif POCO_OS == POCO_OS_ANDROID +#include "Poco/RWLock_Android.h" +#elif defined(POCO_VXWORKS) +#include "Poco/RWLock_VX.h" +#else +#include "Poco/RWLock_POSIX.h" +#endif + + +namespace Poco { + + +class ScopedRWLock; +class ScopedReadRWLock; +class ScopedWriteRWLock; + + +class Foundation_API RWLock: private RWLockImpl + /// A reader writer lock allows multiple concurrent + /// readers or one exclusive writer. +{ +public: + typedef ScopedRWLock ScopedLock; + typedef ScopedReadRWLock ScopedReadLock; + typedef ScopedWriteRWLock ScopedWriteLock; + + RWLock(); + /// Creates the Reader/Writer lock. + + ~RWLock(); + /// Destroys the Reader/Writer lock. + + void readLock(); + /// Acquires a read lock. If another thread currently holds a write lock, + /// waits until the write lock is released. + + bool tryReadLock(); + /// Tries to acquire a read lock. Immediately returns true if successful, or + /// false if another thread currently holds a write lock. + + void writeLock(); + /// Acquires a write lock. If one or more other threads currently hold + /// locks, waits until all locks are released. The results are undefined + /// if the same thread already holds a read or write lock + + bool tryWriteLock(); + /// Tries to acquire a write lock. Immediately returns true if successful, + /// or false if one or more other threads currently hold + /// locks. The result is undefined if the same thread already + /// holds a read or write lock. + + void unlock(); + /// Releases the read or write lock. + +private: + RWLock(const RWLock&); + RWLock& operator = (const RWLock&); +}; + + +class Foundation_API ScopedRWLock + /// A variant of ScopedLock for reader/writer locks. +{ +public: + ScopedRWLock(RWLock& rwl, bool write = false); + ~ScopedRWLock(); + +private: + RWLock& _rwl; + + ScopedRWLock(); + ScopedRWLock(const ScopedRWLock&); + ScopedRWLock& operator = (const ScopedRWLock&); +}; + + +class Foundation_API ScopedReadRWLock : public ScopedRWLock + /// A variant of ScopedLock for reader locks. +{ +public: + ScopedReadRWLock(RWLock& rwl); + ~ScopedReadRWLock(); +}; + + +class Foundation_API ScopedWriteRWLock : public ScopedRWLock + /// A variant of ScopedLock for writer locks. +{ +public: + ScopedWriteRWLock(RWLock& rwl); + ~ScopedWriteRWLock(); +}; + + +// +// inlines +// +inline void RWLock::readLock() +{ + readLockImpl(); +} + + +inline bool RWLock::tryReadLock() +{ + return tryReadLockImpl(); +} + + +inline void RWLock::writeLock() +{ + writeLockImpl(); +} + + +inline bool RWLock::tryWriteLock() +{ + return tryWriteLockImpl(); +} + + +inline void RWLock::unlock() +{ + unlockImpl(); +} + + +inline ScopedRWLock::ScopedRWLock(RWLock& rwl, bool write): _rwl(rwl) +{ + if (write) + _rwl.writeLock(); + else + _rwl.readLock(); +} + + +inline ScopedRWLock::~ScopedRWLock() +{ + try + { + _rwl.unlock(); + } + catch (...) + { + poco_unexpected(); + } +} + + +inline ScopedReadRWLock::ScopedReadRWLock(RWLock& rwl): ScopedRWLock(rwl, false) +{ +} + + +inline ScopedReadRWLock::~ScopedReadRWLock() +{ +} + + +inline ScopedWriteRWLock::ScopedWriteRWLock(RWLock& rwl): ScopedRWLock(rwl, true) +{ +} + + +inline ScopedWriteRWLock::~ScopedWriteRWLock() +{ +} + + +} // namespace Poco + + +#endif // Foundation_RWLock_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RWLock_Android.h b/contrib/libs/poco/Foundation/include/Poco/RWLock_Android.h new file mode 100644 index 0000000000..c6dfc4e5bf --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RWLock_Android.h @@ -0,0 +1,97 @@ +// +// RWLock_Android.h +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLockImpl class for Android Threads. +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RWLock_Android_INCLUDED +#define Foundation_RWLock_Android_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <pthread.h> +#include <errno.h> + + +namespace Poco { + + +class Foundation_API RWLockImpl +{ +protected: + RWLockImpl(); + ~RWLockImpl(); + void readLockImpl(); + bool tryReadLockImpl(); + void writeLockImpl(); + bool tryWriteLockImpl(); + void unlockImpl(); + +private: + pthread_mutex_t _mutex; +}; + + +// +// inlines +// +inline void RWLockImpl::readLockImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot lock reader/writer lock"); +} + + +inline bool RWLockImpl::tryReadLockImpl() +{ + int rc = pthread_mutex_trylock(&_mutex); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock reader/writer lock"); +} + + +inline void RWLockImpl::writeLockImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot lock reader/writer lock"); +} + + +inline bool RWLockImpl::tryWriteLockImpl() +{ + int rc = pthread_mutex_trylock(&_mutex); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock reader/writer lock"); +} + + +inline void RWLockImpl::unlockImpl() +{ + if (pthread_mutex_unlock(&_mutex)) + throw SystemException("cannot unlock reader/writer lock"); +} + + +} // namespace Poco + + +#endif // Foundation_RWLock_Android_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RWLock_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/RWLock_POSIX.h new file mode 100644 index 0000000000..be4d11beb4 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RWLock_POSIX.h @@ -0,0 +1,99 @@ +// +// RWLock_POSIX.h +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLockImpl class for POSIX Threads. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RWLock_POSIX_INCLUDED +#define Foundation_RWLock_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <pthread.h> +#include <errno.h> + + +namespace Poco { + + +class Foundation_API RWLockImpl +{ +protected: + RWLockImpl(); + ~RWLockImpl(); + void readLockImpl(); + bool tryReadLockImpl(); + void writeLockImpl(); + bool tryWriteLockImpl(); + void unlockImpl(); + +private: + pthread_rwlock_t _rwl; +}; + + +// +// inlines +// +inline void RWLockImpl::readLockImpl() +{ + if (pthread_rwlock_rdlock(&_rwl)) + throw SystemException("cannot lock reader/writer lock"); +} + + +inline bool RWLockImpl::tryReadLockImpl() +{ + int rc = pthread_rwlock_tryrdlock(&_rwl); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock reader/writer lock"); + +} + + +inline void RWLockImpl::writeLockImpl() +{ + if (pthread_rwlock_wrlock(&_rwl)) + throw SystemException("cannot lock reader/writer lock"); +} + + +inline bool RWLockImpl::tryWriteLockImpl() +{ + int rc = pthread_rwlock_trywrlock(&_rwl); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock reader/writer lock"); + +} + + +inline void RWLockImpl::unlockImpl() +{ + if (pthread_rwlock_unlock(&_rwl)) + throw SystemException("cannot unlock mutex"); +} + + +} // namespace Poco + + +#endif // Foundation_RWLock_POSIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RWLock_VX.h b/contrib/libs/poco/Foundation/include/Poco/RWLock_VX.h new file mode 100644 index 0000000000..bdc4af2fe2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RWLock_VX.h @@ -0,0 +1,92 @@ +// +// RWLock_VX.h +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLockImpl class for POSIX Threads (VxWorks). +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RWLock_VX_INCLUDED +#define Foundation_RWLock_VX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <pthread.h> +#include <errno.h> + + +namespace Poco { + + +class Foundation_API RWLockImpl +{ +protected: + RWLockImpl(); + ~RWLockImpl(); + void readLockImpl(); + bool tryReadLockImpl(); + void writeLockImpl(); + bool tryWriteLockImpl(); + void unlockImpl(); + +private: + pthread_mutex_t _mutex; +}; + + +// +// inlines +// +inline void RWLockImpl::readLockImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot lock mutex"); +} + + +inline bool RWLockImpl::tryReadLockImpl() +{ + int rc = pthread_mutex_trylock(&_mutex); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock mutex"); + +} + + +inline void RWLockImpl::writeLockImpl() +{ + readLockImpl(); +} + + +inline bool RWLockImpl::tryWriteLockImpl() +{ + return tryReadLockImpl(); + +} + + +inline void RWLockImpl::unlockImpl() +{ + if (pthread_mutex_unlock(&_mutex)) + throw SystemException("cannot unlock mutex"); +} + + +} // namespace Poco + + +#endif // Foundation_RWLock_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RWLock_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/RWLock_WIN32.h new file mode 100644 index 0000000000..e50856e1b4 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RWLock_WIN32.h @@ -0,0 +1,57 @@ +// +// RWLock_WIN32.h +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLockImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RWLock_WIN32_INCLUDED +#define Foundation_RWLock_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API RWLockImpl +{ +protected: + RWLockImpl(); + ~RWLockImpl(); + void readLockImpl(); + bool tryReadLockImpl(); + void writeLockImpl(); + bool tryWriteLockImpl(); + void unlockImpl(); + +private: + void addWriter(); + void removeWriter(); + DWORD tryReadLockOnce(); + + HANDLE _mutex; + HANDLE _readEvent; + HANDLE _writeEvent; + unsigned _readers; + unsigned _writersWaiting; + unsigned _writers; +}; + + +} // namespace Poco + + +#endif // Foundation_RWLock_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RWLock_WINCE.h b/contrib/libs/poco/Foundation/include/Poco/RWLock_WINCE.h new file mode 100644 index 0000000000..d6c8314b24 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RWLock_WINCE.h @@ -0,0 +1,61 @@ +// +// RWLock_WINCE.h +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLockImpl class for WINCE. +// +// Copyright (c) 2009-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RWLock_WINCE_INCLUDED +#define Foundation_RWLock_WINCE_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API RWLockImpl + /// This implementation is based on the one from Stone Steps Inc, + /// licensed under the BSD license. + /// http://forums.stonesteps.ca/thread.asp?t=105 + /// + /// Note that with this implementation, writers always take + /// precedence over readers. +{ +protected: + RWLockImpl(); + ~RWLockImpl(); + void readLockImpl(); + bool tryReadLockImpl(DWORD timeout = 1); + void writeLockImpl(); + bool tryWriteLockImpl(DWORD timeout = 1); + void unlockImpl(); + +private: + DWORD _readerCount; + DWORD _readerWaiting; + DWORD _writerCount; + DWORD _writerWaiting; + HANDLE _readerGreen; + HANDLE _writerGreen; + CRITICAL_SECTION _cs; + bool _writeLock; +}; + + +} // namespace Poco + + +#endif // Foundation_RWLock_WINCE_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Random.h b/contrib/libs/poco/Foundation/include/Poco/Random.h new file mode 100644 index 0000000000..3db078e131 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Random.h @@ -0,0 +1,165 @@ +// +// Random.h +// +// Library: Foundation +// Package: Crypt +// Module: Random +// +// Definition of class Random. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// +// +// Based on the FreeBSD random number generator. +// src/lib/libc/stdlib/random.c,v 1.25 +// +// Copyright (c) 1983, 1993 +// The Regents of the University of California. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 4. Neither the name of the University nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +// SUCH DAMAGE. +// + + +#ifndef Foundation_Random_INCLUDED +#define Foundation_Random_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Random + /// A better random number generator. + /// Random implements a pseudo random number generator + /// (PRNG). The PRNG is a nonlinear additive + /// feedback random number generator using 256 bytes + /// of state information and a period of up to 2^69. +{ +public: + enum Type + { + RND_STATE_0 = 8, /// linear congruential + RND_STATE_32 = 32, /// x**7 + x**3 + 1 + RND_STATE_64 = 64, /// x**15 + x + 1 + RND_STATE_128 = 128, /// x**31 + x**3 + 1 + RND_STATE_256 = 256 /// x**63 + x + 1 + }; + + Random(int stateSize = 256); + /// Creates and initializes the PRNG. + /// Specify either a state buffer size + /// (8 to 256 bytes) or one of the Type values. + + ~Random(); + /// Destroys the PRNG. + + void seed(UInt32 seed); + /// Seeds the pseudo random generator with the given seed. + + void seed(); + /// Seeds the pseudo random generator with a random seed + /// obtained from a RandomInputStream. + + UInt32 next(); + /// Returns the next 31-bit pseudo random number. + + UInt32 next(UInt32 n); + /// Returns the next 31-bit pseudo random number modulo n. + + char nextChar(); + /// Returns the next pseudo random character. + + bool nextBool(); + /// Returns the next boolean pseudo random value. + + float nextFloat(); + /// Returns the next float pseudo random number between 0.0 and 1.0. + + double nextDouble(); + /// Returns the next double pseudo random number between 0.0 and 1.0. + +protected: + void initState(UInt32 seed, char* arg_state, Int32 n); + static UInt32 goodRand(Int32 x); + +private: + enum + { + MAX_TYPES = 5, + NSHUFF = 50 + }; + + UInt32* _fptr; + UInt32* _rptr; + UInt32* _state; + int _randType; + int _randDeg; + int _randSep; + UInt32* _endPtr; + char* _pBuffer; +}; + + +// +// inlines +// +inline UInt32 Random::next(UInt32 n) +{ + return next() % n; +} + + +inline char Random::nextChar() +{ + return char((next() >> 3) & 0xFF); +} + + +inline bool Random::nextBool() +{ + return (next() & 0x1000) != 0; +} + + +inline float Random::nextFloat() +{ + return float(next()) / 0x7FFFFFFF; +} + + +inline double Random::nextDouble() +{ + return double(next()) / 0x7FFFFFFF; +} + + +} // namespace Poco + + +#endif // Foundation_Random_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RandomStream.h b/contrib/libs/poco/Foundation/include/Poco/RandomStream.h new file mode 100644 index 0000000000..152b95c835 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RandomStream.h @@ -0,0 +1,73 @@ +// +// RandomStream.h +// +// Library: Foundation +// Package: Crypt +// Module: RandomStream +// +// Definition of class RandomInputStream. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RandomStream_INCLUDED +#define Foundation_RandomStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedStreamBuf.h" +#include <istream> + + +namespace Poco { + + +class Foundation_API RandomBuf: public BufferedStreamBuf + /// This streambuf generates random data. + /// On Windows NT, the cryptographic API is used. + /// On Unix, /dev/random is used, if available. + /// Otherwise, a random number generator, some + /// more-or-less random data and a SHA-1 digest + /// is used to generate random data. +{ +public: + RandomBuf(); + ~RandomBuf(); + int readFromDevice(char* buffer, std::streamsize length); +}; + + +class Foundation_API RandomIOS: public virtual std::ios + /// The base class for RandomInputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + RandomIOS(); + ~RandomIOS(); + RandomBuf* rdbuf(); + +protected: + RandomBuf _buf; +}; + + +class Foundation_API RandomInputStream: public RandomIOS, public std::istream + /// This istream generates random data + /// using the RandomBuf. +{ +public: + RandomInputStream(); + ~RandomInputStream(); +}; + + +} // namespace Poco + + +#endif // Foundation_RandomStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RecursiveDirectoryIterator.h b/contrib/libs/poco/Foundation/include/Poco/RecursiveDirectoryIterator.h new file mode 100644 index 0000000000..c0ce2285ee --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RecursiveDirectoryIterator.h @@ -0,0 +1,254 @@ +// +// RecursiveDirectoryIterator.h +// +// Library: Foundation +// Package: Filesystem +// Module: RecursiveDirectoryIterator +// +// Definition of the RecursiveDirectoryIterator class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RecursiveDirectoryIterator_INCLUDED +#define Foundation_RecursiveDirectoryIterator_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/File.h" +#include "Poco/Path.h" +#include "Poco/RecursiveDirectoryIteratorImpl.h" +#include "Poco/DirectoryIteratorStrategy.h" + + +namespace Poco { + + +class DirectoryIterator; + + +template<class TTravStr> +class RecursiveDirectoryIteratorImpl; + + +template<class TTravStr = ChildrenFirstTraverse> +class RecursiveDirectoryIterator + /// The RecursiveDirectoryIterator class is used to enumerate + /// all files in a directory and its subdirectories. + /// + /// RecursiveDirectoryIterator has some limitations: + /// * only forward iteration (++) is supported + /// * an iterator copied from another one will always + /// point to the same file as the original iterator, + /// even is the original iterator has been advanced + /// (all copies of an iterator share their state with + /// the original iterator) + /// + /// The class can follow different traversal strategies: + /// * depth-first strategy; + /// * siblings-first strategy. + /// The stategies are set by template parameter. + /// There are two corresponding typedefs: + /// * SimpleRecursiveDirectoryIterator; + /// * SiblingsFirstRecursiveDirectoryIterator. + /// + /// The depth of traversal can be limited by constructor + /// parameter maxDepth (which sets the infinite depth by default). +{ +public: + typedef RecursiveDirectoryIterator<TTravStr> MyType; + + enum + { + D_INFINITE = 0 /// Constant for infinite traverse depth. + }; + + RecursiveDirectoryIterator() + /// Creates the end iterator. + : _pImpl(0) + { + } + + RecursiveDirectoryIterator(const std::string& path, UInt16 maxDepth = D_INFINITE) + /// Creates a recursive directory iterator for the given path. + : _pImpl(new ImplType(path, maxDepth)), _path(Path(_pImpl->get())), _file(_path) + { + } + + RecursiveDirectoryIterator(const MyType& iterator): + /// Creates a copy of another recursive directory iterator. + _pImpl(iterator._pImpl), _path(iterator._path), _file(iterator._file) + { + } + + RecursiveDirectoryIterator(const DirectoryIterator& iterator, UInt16 maxDepth = D_INFINITE): + /// Creates a recursive directory iterator for the path of + /// non-recursive directory iterator. + _pImpl(new ImplType(iterator->path(), maxDepth)), _path(Path(_pImpl->get())), _file(_path) + { + } + + RecursiveDirectoryIterator(const File& file, UInt16 maxDepth = D_INFINITE): + /// Creates a recursive directory iterator for the given path. + _pImpl(new ImplType(file.path(), maxDepth)), _path(Path(_pImpl->get())), _file(_path) + { + } + + RecursiveDirectoryIterator(const Path& path, UInt16 maxDepth = D_INFINITE): + /// Creates a recursive directory iterator for the given path. + _pImpl(new ImplType(path.toString(), maxDepth)), _path(Path(_pImpl->get())), _file(_path) + { + } + + ~RecursiveDirectoryIterator() + /// Destroys the DirectoryIterator. + { + if (_pImpl) + _pImpl->release(); + } + + const std::string& name() const + /// Returns the current filename. + { + return _path.getFileName(); + } + + const Poco::Path& path() const + /// Returns the current path. + { + return _path; + } + + UInt16 depth() const + /// Depth of recursion (counting from 1). + { + return _pImpl->depth(); + } + + UInt16 maxDepth() const + /// Max depth of recursion (counting from 1). + { + return _pImpl->maxDepth(); + } + + + MyType& operator = (const MyType& it) + { + if (_pImpl) + _pImpl->release(); + _pImpl = it._pImpl; + if (_pImpl) + { + _pImpl->duplicate(); + _path = it._path; + _file = _path; + } + return *this; + } + + MyType& operator = (const File& file) + { + if (_pImpl) + _pImpl->release(); + _pImpl = new ImplType(file.path()); + _path = Path(_pImpl->get()); + _file = _path; + return *this; + } + + + MyType& operator = (const Path& path) + { + if (_pImpl) + _pImpl->release(); + _pImpl = new ImplType(path.toString()); + _path = Path(_pImpl->get()); + _file = _path; + return *this; + } + + MyType& operator = (const std::string& path) + { + if (_pImpl) + _pImpl->release(); + _pImpl = new ImplType(path); + _path = Path(_pImpl->get()); + _file = _path; + return *this; + } + + MyType& operator ++ () + { + if (_pImpl) + { + _path = Path(_pImpl->next()); + _file = _path; + } + return *this; + } + + const File& operator * () const + { + return _file; + } + + File& operator *() + { + return _file; + } + + const File* operator -> () const + { + return &_file; + } + + File* operator -> () + { + return &_file; + } + + template<class T1, class T2> + friend inline bool operator ==(const RecursiveDirectoryIterator<T1>& a, const RecursiveDirectoryIterator<T2>& b); + template<class T1, class T2> + friend inline bool operator !=(const RecursiveDirectoryIterator<T1>& a, const RecursiveDirectoryIterator<T2>& b); + +private: + typedef RecursiveDirectoryIteratorImpl<TTravStr> ImplType; + + ImplType* _pImpl; + Path _path; + File _file; +}; + + +// +// friend comparsion operators +// +template<class T1, class T2> +inline bool operator ==(const RecursiveDirectoryIterator<T1>& a, const RecursiveDirectoryIterator<T2>& b) +{ + return a.path().toString() == b.path().toString();; +} + +template<class T1, class T2> +inline bool operator !=(const RecursiveDirectoryIterator<T1>& a, const RecursiveDirectoryIterator<T2>& b) +{ + return a.path().toString() != b.path().toString();; +} + + +// +// typedefs +// +typedef RecursiveDirectoryIterator<ChildrenFirstTraverse> SimpleRecursiveDirectoryIterator; +typedef RecursiveDirectoryIterator<SiblingsFirstTraverse> SiblingsFirstRecursiveDirectoryIterator; + + +} // namespace Poco + + +#endif // Foundation_RecursiveDirectoryIterator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RecursiveDirectoryIteratorImpl.h b/contrib/libs/poco/Foundation/include/Poco/RecursiveDirectoryIteratorImpl.h new file mode 100644 index 0000000000..fb2d467049 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RecursiveDirectoryIteratorImpl.h @@ -0,0 +1,111 @@ +// +// RecursiveDirectoryIteratorImpl.h +// +// Library: Foundation +// Package: Filesystem +// Module: RecursiveDirectoryIterator +// +// Definition of the RecursiveDirectoryIteratorImpl class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RecursiveDirectoryIteratorImpl_INCLUDED +#define Foundation_RecursiveDirectoryIteratorImpl_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DirectoryIteratorStrategy.h" +#include <stack> +#include <functional> + + +namespace Poco { + + +class ChildrenFirstTraverse; +class SiblingsFirstTraverse; + + +template<class TTraverseStrategy = ChildrenFirstTraverse> +class RecursiveDirectoryIteratorImpl +{ +public: + enum + { + D_INFINITE = 0 /// Special value for infinite traverse depth. + }; + + RecursiveDirectoryIteratorImpl(const std::string& path, UInt16 maxDepth = D_INFINITE) + : _maxDepth(maxDepth), _traverseStrategy(std::ptr_fun(depthFun), _maxDepth), _isFinished(false), _rc(1) + { + _itStack.push(DirectoryIterator(path)); + _current = _itStack.top()->path(); + } + + ~RecursiveDirectoryIteratorImpl() + { + } + + inline void duplicate() + { + ++_rc; + } + + inline void release() + { + if (--_rc == 0) + delete this; + } + + inline UInt16 depth() const + { + return depthFun(_itStack); + } + + inline UInt16 maxDepth() const + { + return _maxDepth; + } + + inline const std::string& get() const + { + return _current; + } + const std::string& next() + { + if (_isFinished) + return _current; + + _current = _traverseStrategy.next(&_itStack, &_isFinished); + + return _current; + } + +private: + typedef std::stack<DirectoryIterator> Stack; + + static UInt16 depthFun(const Stack& stack) + /// Function which implements the logic of determining + /// recursion depth. + { + return static_cast<Poco::UInt16>(stack.size()); + } + + UInt16 _maxDepth; + TTraverseStrategy _traverseStrategy; + bool _isFinished; + Stack _itStack; + std::string _current; + int _rc; +}; + + +} // namespace Poco + + +#endif // Foundation_RecursiveDirectoryIteratorImpl_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RefCountedObject.h b/contrib/libs/poco/Foundation/include/Poco/RefCountedObject.h new file mode 100644 index 0000000000..55ea76a167 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RefCountedObject.h @@ -0,0 +1,94 @@ +// +// RefCountedObject.h +// +// Library: Foundation +// Package: Core +// Module: RefCountedObject +// +// Definition of the RefCountedObject class. +// +// Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RefCountedObject_INCLUDED +#define Foundation_RefCountedObject_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AtomicCounter.h" + + +namespace Poco { + + +class Foundation_API RefCountedObject + /// A base class for objects that employ + /// reference counting based garbage collection. + /// + /// Reference-counted objects inhibit construction + /// by copying and assignment. +{ +public: + RefCountedObject(); + /// Creates the RefCountedObject. + /// The initial reference count is one. + + void duplicate() const; + /// Increments the object's reference count. + + void release() const noexcept; + /// Decrements the object's reference count + /// and deletes the object if the count + /// reaches zero. + + int referenceCount() const; + /// Returns the reference count. + +protected: + virtual ~RefCountedObject(); + /// Destroys the RefCountedObject. + +private: + RefCountedObject(const RefCountedObject&); + RefCountedObject& operator = (const RefCountedObject&); + + mutable AtomicCounter _counter; +}; + + +// +// inlines +// +inline int RefCountedObject::referenceCount() const +{ + return _counter.value(); +} + + +inline void RefCountedObject::duplicate() const +{ + ++_counter; +} + + +inline void RefCountedObject::release() const noexcept +{ + try + { + if (--_counter == 0) delete this; + } + catch (...) + { + poco_unexpected(); + } +} + + +} // namespace Poco + + +#endif // Foundation_RefCountedObject_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RegularExpression.h b/contrib/libs/poco/Foundation/include/Poco/RegularExpression.h new file mode 100644 index 0000000000..638b99e11b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RegularExpression.h @@ -0,0 +1,247 @@ +// +// RegularExpression.h +// +// Library: Foundation +// Package: RegExp +// Module: RegularExpression +// +// Definitions of class RegularExpression. +// +// A wrapper class for Philip Hazel's PCRE - Perl Compatible Regular Expressions +// library (http://www.pcre.org). +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RegularExpression_INCLUDED +#define Foundation_RegularExpression_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> + + +namespace Poco { + + +class Foundation_API RegularExpression + /// A class for working with regular expressions. + /// Implemented using PCRE, the Perl Compatible + /// Regular Expressions library by Philip Hazel + /// (see http://www.pcre.org). +{ +public: + enum Options // These must match the corresponding options in pcre.h! + /// Some of the following options can only be passed to the constructor; + /// some can be passed only to matching functions, and some can be used + /// everywhere. + /// + /// * Options marked [ctor] can be passed to the constructor. + /// * Options marked [match] can be passed to match, extract, split and subst. + /// * Options marked [subst] can be passed to subst. + /// + /// See the PCRE documentation for more information. + { + RE_CASELESS = 0x00000001, /// case insensitive matching (/i) [ctor] + RE_MULTILINE = 0x00000002, /// enable multi-line mode; affects ^ and $ (/m) [ctor] + RE_DOTALL = 0x00000004, /// dot matches all characters, including newline (/s) [ctor] + RE_EXTENDED = 0x00000008, /// totally ignore whitespace (/x) [ctor] + RE_ANCHORED = 0x00000010, /// treat pattern as if it starts with a ^ [ctor, match] + RE_DOLLAR_ENDONLY = 0x00000020, /// dollar matches end-of-string only, not last newline in string [ctor] + RE_EXTRA = 0x00000040, /// enable optional PCRE functionality [ctor] + RE_NOTBOL = 0x00000080, /// circumflex does not match beginning of string [match] + RE_NOTEOL = 0x00000100, /// $ does not match end of string [match] + RE_UNGREEDY = 0x00000200, /// make quantifiers ungreedy [ctor] + RE_NOTEMPTY = 0x00000400, /// empty string never matches [match] + RE_UTF8 = 0x00000800, /// assume pattern and subject is UTF-8 encoded [ctor] + RE_NO_AUTO_CAPTURE = 0x00001000, /// disable numbered capturing parentheses [ctor, match] + RE_NO_UTF8_CHECK = 0x00002000, /// do not check validity of UTF-8 code sequences [match] + RE_FIRSTLINE = 0x00040000, /// an unanchored pattern is required to match + /// before or at the first newline in the subject string, + /// though the matched text may continue over the newline [ctor] + RE_DUPNAMES = 0x00080000, /// names used to identify capturing subpatterns need not be unique [ctor] + RE_NEWLINE_CR = 0x00100000, /// assume newline is CR ('\r'), the default [ctor] + RE_NEWLINE_LF = 0x00200000, /// assume newline is LF ('\n') [ctor] + RE_NEWLINE_CRLF = 0x00300000, /// assume newline is CRLF ("\r\n") [ctor] + RE_NEWLINE_ANY = 0x00400000, /// assume newline is any valid Unicode newline character [ctor] + RE_NEWLINE_ANYCRLF = 0x00500000, /// assume newline is any of CR, LF, CRLF [ctor] + RE_GLOBAL = 0x10000000, /// replace all occurences (/g) [subst] + RE_NO_VARS = 0x20000000 /// treat dollar in replacement string as ordinary character [subst] + }; + + struct Match + { + std::string::size_type offset; /// zero based offset (std::string::npos if subexpr does not match) + std::string::size_type length; /// length of substring + }; + typedef std::vector<Match> MatchVec; + + RegularExpression(const std::string& pattern, int options = 0, bool study = true); + /// Creates a regular expression and parses the given pattern. + /// If study is true, the pattern is analyzed and optimized. This + /// is mainly useful if the pattern is used more than once. + /// For a description of the options, please see the PCRE documentation. + /// Throws a RegularExpressionException if the patter cannot be compiled. + + ~RegularExpression(); + /// Destroys the regular expression. + + int match(const std::string& subject, Match& mtch, int options = 0) const; + /// Matches the given subject string against the pattern. Returns the position + /// of the first captured substring in mtch. + /// If no part of the subject matches the pattern, mtch.offset is std::string::npos and + /// mtch.length is 0. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int match(const std::string& subject, std::string::size_type offset, Match& mtch, int options = 0) const; + /// Matches the given subject string, starting at offset, against the pattern. + /// Returns the position of the captured substring in mtch. + /// If no part of the subject matches the pattern, mtch.offset is std::string::npos and + /// mtch.length is 0. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int match(const std::string& subject, std::string::size_type offset, MatchVec& matches, int options = 0) const; + /// Matches the given subject string against the pattern. + /// The first entry in matches contains the position of the captured substring. + /// The following entries identify matching subpatterns. See the PCRE documentation + /// for a more detailed explanation. + /// If no part of the subject matches the pattern, matches is empty. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + bool match(const std::string& subject, std::string::size_type offset = 0) const; + /// Returns true if and only if the subject matches the regular expression. + /// + /// Internally, this method sets the RE_ANCHORED and RE_NOTEMPTY options for + /// matching, which means that the empty string will never match and + /// the pattern is treated as if it starts with a ^. + + bool match(const std::string& subject, std::string::size_type offset, int options) const; + /// Returns true if and only if the subject matches the regular expression. + + bool operator == (const std::string& subject) const; + /// Returns true if and only if the subject matches the regular expression. + /// + /// Internally, this method sets the RE_ANCHORED and RE_NOTEMPTY options for + /// matching, which means that the empty string will never match and + /// the pattern is treated as if it starts with a ^. + + bool operator != (const std::string& subject) const; + /// Returns true if and only if the subject does not match the regular expression. + /// + /// Internally, this method sets the RE_ANCHORED and RE_NOTEMPTY options for + /// matching, which means that the empty string will never match and + /// the pattern is treated as if it starts with a ^. + + int extract(const std::string& subject, std::string& str, int options = 0) const; + /// Matches the given subject string against the pattern. + /// Returns the captured string. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int extract(const std::string& subject, std::string::size_type offset, std::string& str, int options = 0) const; + /// Matches the given subject string, starting at offset, against the pattern. + /// Returns the captured string. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int split(const std::string& subject, std::vector<std::string>& strings, int options = 0) const; + /// Matches the given subject string against the pattern. + /// The first entry in captured is the captured substring. + /// The following entries contain substrings matching subpatterns. See the PCRE documentation + /// for a more detailed explanation. + /// If no part of the subject matches the pattern, captured is empty. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int split(const std::string& subject, std::string::size_type offset, std::vector<std::string>& strings, int options = 0) const; + /// Matches the given subject string against the pattern. + /// The first entry in captured is the captured substring. + /// The following entries contain substrings matching subpatterns. See the PCRE documentation + /// for a more detailed explanation. + /// If no part of the subject matches the pattern, captured is empty. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int subst(std::string& subject, const std::string& replacement, int options = 0) const; + /// Substitute in subject all matches of the pattern with replacement. + /// If RE_GLOBAL is specified as option, all matches are replaced. Otherwise, + /// only the first match is replaced. + /// Occurrences of $<n> (for example, $1, $2, ...) in replacement are replaced + /// with the corresponding captured string. $0 is the original subject string. + /// Returns the number of replaced occurrences. + + int subst(std::string& subject, std::string::size_type offset, const std::string& replacement, int options = 0) const; + /// Substitute in subject all matches of the pattern with replacement, + /// starting at offset. + /// If RE_GLOBAL is specified as option, all matches are replaced. Otherwise, + /// only the first match is replaced. + /// Unless RE_NO_VARS is specified, occurrences of $<n> (for example, $0, $1, $2, ... $9) + /// in replacement are replaced with the corresponding captured string. + /// $0 is the captured substring. $1 ... $n are the substrings matching the subpatterns. + /// Returns the number of replaced occurrences. + + static bool match(const std::string& subject, const std::string& pattern, int options = 0); + /// Matches the given subject string against the regular expression given in pattern, + /// using the given options. + +protected: + std::string::size_type substOne(std::string& subject, std::string::size_type offset, const std::string& replacement, int options) const; + +private: + // Note: to avoid a dependency on the pcre.h header the following are + // declared as void* and casted to the correct type in the implementation file. + void* _pcre; // Actual type is pcre* + void* _extra; // Actual type is struct pcre_extra* + + static const int OVEC_SIZE; + + RegularExpression(); + RegularExpression(const RegularExpression&); + RegularExpression& operator = (const RegularExpression&); +}; + + +// +// inlines +// +inline int RegularExpression::match(const std::string& subject, Match& mtch, int options) const +{ + return match(subject, 0, mtch, options); +} + + +inline int RegularExpression::split(const std::string& subject, std::vector<std::string>& strings, int options) const +{ + return split(subject, 0, strings, options); +} + + +inline int RegularExpression::subst(std::string& subject, const std::string& replacement, int options) const +{ + return subst(subject, 0, replacement, options); +} + + +inline bool RegularExpression::operator == (const std::string& subject) const +{ + return match(subject); +} + + +inline bool RegularExpression::operator != (const std::string& subject) const +{ + return !match(subject); +} + + +} // namespace Poco + + +#endif // Foundation_RegularExpression_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RotateStrategy.h b/contrib/libs/poco/Foundation/include/Poco/RotateStrategy.h new file mode 100644 index 0000000000..82c331f1f6 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RotateStrategy.h @@ -0,0 +1,165 @@ +// +// RotateStrategy.h +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Definition of the RotateStrategy class and subclasses. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RotateStrategy_INCLUDED +#define Foundation_RotateStrategy_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timespan.h" +#include "Poco/Timestamp.h" +#include "Poco/Exception.h" +#include "Poco/LogFile.h" +#include "Poco/StringTokenizer.h" +#include "Poco/DateTimeParser.h" +#include "Poco/NumberParser.h" + + +namespace Poco { + + +class Foundation_API RotateStrategy + /// The RotateStrategy is used by LogFile to determine when + /// a file must be rotated. +{ +public: + RotateStrategy(); + virtual ~RotateStrategy(); + + virtual bool mustRotate(LogFile* pFile) = 0; + /// Returns true if the given log file must + /// be rotated, false otherwise. + +private: + RotateStrategy(const RotateStrategy&); + RotateStrategy& operator = (const RotateStrategy&); +}; + + +template <class DT> +class RotateAtTimeStrategy: public RotateStrategy + /// The file is rotated at specified [day,][hour]:minute +{ +public: + RotateAtTimeStrategy(const std::string& rtime): + _day(-1), + _hour(-1), + _minute(0) + { + if (rtime.empty()) + throw InvalidArgumentException("Rotation time must be specified."); + + if ((rtime.find(',') != rtime.npos) && (rtime.find(':') == rtime.npos)) + throw InvalidArgumentException("Invalid rotation time specified."); + + StringTokenizer timestr(rtime, ",:", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + int index = 0; + + switch (timestr.count()) + { + case 3: // day,hh:mm + { + std::string::const_iterator it = timestr[index].begin(); + _day = DateTimeParser::parseDayOfWeek(it, timestr[index].end()); + ++index; + } + case 2: // hh:mm + _hour = NumberParser::parse(timestr[index]); + ++index; + case 1: // mm + _minute = NumberParser::parse(timestr[index]); + break; + default: + throw InvalidArgumentException("Invalid rotation time specified."); + } + getNextRollover(); + } + + ~RotateAtTimeStrategy() + { + } + + bool mustRotate(LogFile* /*pFile*/) + { + if (DT() >= _threshold) + { + getNextRollover(); + return true; + } + return false; + } + +private: + void getNextRollover() + { + Timespan tsp(0, 0, 1, 0, 1000); // 0,00:01:00.001 + do + { + _threshold += tsp; + } + while (!(_threshold.minute() == _minute && + (-1 == _hour || _threshold.hour() == _hour) && + (-1 == _day || _threshold.dayOfWeek() == _day))); + // round to :00.0 seconds + _threshold.assign(_threshold.year(), _threshold.month(), _threshold.day(), _threshold.hour(), _threshold.minute()); + } + + DT _threshold; + int _day; + int _hour; + int _minute; +}; + + +class Foundation_API RotateByIntervalStrategy: public RotateStrategy + /// The file is rotated when the log file + /// exceeds a given age. + /// + /// For this to work reliably across all platforms and file systems + /// (there are severe issues on most platforms finding out the real + /// creation date of a file), the creation date of the file is + /// written into the log file as the first entry. +{ +public: + RotateByIntervalStrategy(const Timespan& span); + ~RotateByIntervalStrategy(); + bool mustRotate(LogFile* pFile); + +private: + Timespan _span; + Timestamp _lastRotate; + static const std::string ROTATE_TEXT; +}; + + +class Foundation_API RotateBySizeStrategy: public RotateStrategy + /// The file is rotated when the log file + /// exceeds a given size. +{ +public: + RotateBySizeStrategy(UInt64 size); + ~RotateBySizeStrategy(); + bool mustRotate(LogFile* pFile); + +private: + UInt64 _size; +}; + + +} // namespace Poco + + +#endif // Foundation_RotateStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Runnable.h b/contrib/libs/poco/Foundation/include/Poco/Runnable.h new file mode 100644 index 0000000000..c87a628170 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Runnable.h @@ -0,0 +1,45 @@ +// +// Runnable.h +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the Runnable class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Runnable_INCLUDED +#define Foundation_Runnable_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Runnable + /// The Runnable interface with the run() method + /// must be implemented by classes that provide + /// an entry point for a thread. +{ +public: + Runnable(); + virtual ~Runnable(); + + virtual void run() = 0; + /// Do whatever the thread needs to do. Must + /// be overridden by subclasses. +}; + + +} // namespace Poco + + +#endif // Foundation_Runnable_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/RunnableAdapter.h b/contrib/libs/poco/Foundation/include/Poco/RunnableAdapter.h new file mode 100644 index 0000000000..571871be98 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/RunnableAdapter.h @@ -0,0 +1,78 @@ +// +// RunnableAdapter.h +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the RunnableAdapter template class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_RunnableAdapter_INCLUDED +#define Foundation_RunnableAdapter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" + + +namespace Poco { + + +template <class C> +class RunnableAdapter: public Runnable + /// This adapter simplifies using ordinary methods as + /// targets for threads. + /// Usage: + /// RunnableAdapter<MyClass> ra(myObject, &MyObject::doSomething)); + /// Thread thr; + /// thr.Start(ra); + /// + /// For using a freestanding or static member function as a thread + /// target, please see the ThreadTarget class. +{ +public: + typedef void (C::*Callback)(); + + RunnableAdapter(C& object, Callback method): _pObject(&object), _method(method) + { + } + + RunnableAdapter(const RunnableAdapter& ra): _pObject(ra._pObject), _method(ra._method) + { + } + + ~RunnableAdapter() + { + } + + RunnableAdapter& operator = (const RunnableAdapter& ra) + { + _pObject = ra._pObject; + _method = ra._method; + return *this; + } + + void run() + { + (_pObject->*_method)(); + } + +private: + RunnableAdapter(); + + C* _pObject; + Callback _method; +}; + + +} // namespace Poco + + +#endif // Foundation_RunnableAdapter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SHA1Engine.h b/contrib/libs/poco/Foundation/include/Poco/SHA1Engine.h new file mode 100644 index 0000000000..81c8a4d9ea --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SHA1Engine.h @@ -0,0 +1,81 @@ +// +// SHA1Engine.h +// +// Library: Foundation +// Package: Crypt +// Module: SHA1Engine +// +// Definition of class SHA1Engine. +// +// Secure Hash Standard SHA-1 algorithm +// (FIPS 180-1, see http://www.itl.nist.gov/fipspubs/fip180-1.htm) +// +// Based on the public domain implementation by Peter C. Gutmann +// on 2 Sep 1992, modified by Carl Ellison to be SHA-1. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SHA1Engine_INCLUDED +#define Foundation_SHA1Engine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" + + +namespace Poco { + + +class Foundation_API SHA1Engine: public DigestEngine + /// This class implementes the SHA-1 message digest algorithm. + /// (FIPS 180-1, see http://www.itl.nist.gov/fipspubs/fip180-1.htm) +{ +public: + enum + { + BLOCK_SIZE = 64, + DIGEST_SIZE = 20 + }; + + SHA1Engine(); + ~SHA1Engine(); + + std::size_t digestLength() const; + void reset(); + const DigestEngine::Digest& digest(); + +protected: + void updateImpl(const void* data, std::size_t length); + +private: + void transform(); + static void byteReverse(UInt32* buffer, int byteCount); + + typedef UInt8 BYTE; + + struct Context + { + UInt32 digest[5]; // Message digest + UInt32 countLo; // 64-bit bit count + UInt32 countHi; + UInt32 data[16]; // SHA data buffer + UInt32 slop; // # of bytes saved in data[] + }; + + Context _context; + DigestEngine::Digest _digest; + + SHA1Engine(const SHA1Engine&); + SHA1Engine& operator = (const SHA1Engine&); +}; + + +} // namespace Poco + + +#endif // Foundation_SHA1Engine_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ScopedLock.h b/contrib/libs/poco/Foundation/include/Poco/ScopedLock.h new file mode 100644 index 0000000000..483f821f5b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ScopedLock.h @@ -0,0 +1,121 @@ +// +// ScopedLock.h +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the ScopedLock template class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ScopedLock_INCLUDED +#define Foundation_ScopedLock_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template <class M> +class ScopedLock + /// A class that simplifies thread synchronization + /// with a mutex. + /// The constructor accepts a Mutex (and optionally + /// a timeout value in milliseconds) and locks it. + /// The destructor unlocks the mutex. +{ +public: + explicit ScopedLock(M& mtx): _mutex(mtx) + { + _mutex.lock(); + } + + ScopedLock(M& mutex, long milliseconds): _mutex(mutex) + { + _mutex.lock(milliseconds); + } + + ~ScopedLock() + { + try + { + _mutex.unlock(); + } + catch (...) + { + poco_unexpected(); + } + } + +private: + M& _mutex; + + ScopedLock(); + ScopedLock(const ScopedLock&); + ScopedLock& operator = (const ScopedLock&); +}; + + +template <class M> +class ScopedLockWithUnlock + /// A class that simplifies thread synchronization + /// with a mutex. + /// The constructor accepts a Mutex (and optionally + /// a timeout value in milliseconds) and locks it. + /// The destructor unlocks the mutex. + /// The unlock() member function allows for manual + /// unlocking of the mutex. +{ +public: + explicit ScopedLockWithUnlock(M& mutex): _pMutex(&mutex) + { + _pMutex->lock(); + } + + ScopedLockWithUnlock(M& mutex, long milliseconds): _pMutex(&mutex) + { + _pMutex->lock(milliseconds); + } + + ~ScopedLockWithUnlock() + { + try + { + unlock(); + } + catch (...) + { + poco_unexpected(); + } + } + + void unlock() + { + if (_pMutex) + { + _pMutex->unlock(); + _pMutex = 0; + } + } + +private: + M* _pMutex; + + ScopedLockWithUnlock(); + ScopedLockWithUnlock(const ScopedLockWithUnlock&); + ScopedLockWithUnlock& operator = (const ScopedLockWithUnlock&); +}; + + +} // namespace Poco + + +#endif // Foundation_ScopedLock_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ScopedUnlock.h b/contrib/libs/poco/Foundation/include/Poco/ScopedUnlock.h new file mode 100644 index 0000000000..a62fbb33b0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ScopedUnlock.h @@ -0,0 +1,64 @@ +// +// ScopedUnlock.h +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the ScopedUnlock template class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ScopedUnlock_INCLUDED +#define Foundation_ScopedUnlock_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template <class M> +class ScopedUnlock + /// A class that simplifies thread synchronization + /// with a mutex. + /// The constructor accepts a Mutex and unlocks it. + /// The destructor locks the mutex. +{ +public: + inline ScopedUnlock(M& mutex, bool unlockNow = true): _mutex(mutex) + { + if (unlockNow) + _mutex.unlock(); + } + inline ~ScopedUnlock() + { + try + { + _mutex.lock(); + } + catch (...) + { + poco_unexpected(); + } + } + +private: + M& _mutex; + + ScopedUnlock(); + ScopedUnlock(const ScopedUnlock&); + ScopedUnlock& operator = (const ScopedUnlock&); +}; + + +} // namespace Poco + + +#endif // Foundation_ScopedUnlock_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Semaphore.h b/contrib/libs/poco/Foundation/include/Poco/Semaphore.h new file mode 100644 index 0000000000..7c10c4afe4 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Semaphore.h @@ -0,0 +1,137 @@ +// +// Semaphore.h +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Definition of the Semaphore class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Semaphore_INCLUDED +#define Foundation_Semaphore_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/Semaphore_WIN32.h" +#elif defined(POCO_VXWORKS) +#include "Poco/Semaphore_VX.h" +#else +#include "Poco/Semaphore_POSIX.h" +#endif + + +namespace Poco { + + +class Foundation_API Semaphore: private SemaphoreImpl + /// A Semaphore is a synchronization object with the following + /// characteristics: + /// A semaphore has a value that is constrained to be a non-negative + /// integer and two atomic operations. The allowable operations are V + /// (here called set()) and P (here called wait()). A V (set()) operation + /// increases the value of the semaphore by one. + /// A P (wait()) operation decreases the value of the semaphore by one, + /// provided that can be done without violating the constraint that the + /// value be non-negative. A P (wait()) operation that is initiated when + /// the value of the semaphore is 0 suspends the calling thread. + /// The calling thread may continue when the value becomes positive again. +{ +public: + Semaphore(int n); + Semaphore(int n, int max); + /// Creates the semaphore. The current value + /// of the semaphore is given in n. The + /// maximum value of the semaphore is given + /// in max. + /// If only n is given, it must be greater than + /// zero. + /// If both n and max are given, max must be + /// greater than zero, n must be greater than + /// or equal to zero and less than or equal + /// to max. + + ~Semaphore(); + /// Destroys the semaphore. + + void set(); + /// Increments the semaphore's value by one and + /// thus signals the semaphore. Another thread + /// waiting for the semaphore will be able + /// to continue. + + void wait(); + /// Waits for the semaphore to become signalled. + /// To become signalled, a semaphore's value must + /// be greater than zero. + /// Decrements the semaphore's value by one. + + void wait(long milliseconds); + /// Waits for the semaphore to become signalled. + /// To become signalled, a semaphore's value must + /// be greater than zero. + /// Throws a TimeoutException if the semaphore + /// does not become signalled within the specified + /// time interval. + /// Decrements the semaphore's value by one + /// if successful. + + bool tryWait(long milliseconds); + /// Waits for the semaphore to become signalled. + /// To become signalled, a semaphore's value must + /// be greater than zero. + /// Returns true if the semaphore + /// became signalled within the specified + /// time interval, false otherwise. + /// Decrements the semaphore's value by one + /// if successful. + +private: + Semaphore(); + Semaphore(const Semaphore&); + Semaphore& operator = (const Semaphore&); +}; + + +// +// inlines +// +inline void Semaphore::set() +{ + setImpl(); +} + + +inline void Semaphore::wait() +{ + waitImpl(); +} + + +inline void Semaphore::wait(long milliseconds) +{ + if (!waitImpl(milliseconds)) + throw TimeoutException(); +} + + +inline bool Semaphore::tryWait(long milliseconds) +{ + return waitImpl(milliseconds); +} + + +} // namespace Poco + + +#endif // Foundation_Semaphore_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Semaphore_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/Semaphore_POSIX.h new file mode 100644 index 0000000000..3fc0897faf --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Semaphore_POSIX.h @@ -0,0 +1,75 @@ +// +// Semaphore_POSIX.h +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Definition of the SemaphoreImpl class for POSIX Threads. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Semaphore_POSIX_INCLUDED +#define Foundation_Semaphore_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <pthread.h> +#include <errno.h> + + +namespace Poco { + + +class Foundation_API SemaphoreImpl +{ +protected: + SemaphoreImpl(int n, int max); + ~SemaphoreImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + +private: + volatile int _n; + int _max; + pthread_mutex_t _mutex; + pthread_cond_t _cond; +}; + + +// +// inlines +// +inline void SemaphoreImpl::setImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot signal semaphore (lock)"); + if (_n < _max) + { + ++_n; + } + else + { + pthread_mutex_unlock(&_mutex); + throw SystemException("cannot signal semaphore: count would exceed maximum"); + } + if (pthread_cond_signal(&_cond)) + { + pthread_mutex_unlock(&_mutex); + throw SystemException("cannot signal semaphore"); + } + pthread_mutex_unlock(&_mutex); +} + + +} // namespace Poco + + +#endif // Foundation_Semaphore_POSIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Semaphore_VX.h b/contrib/libs/poco/Foundation/include/Poco/Semaphore_VX.h new file mode 100644 index 0000000000..181afe2f5c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Semaphore_VX.h @@ -0,0 +1,56 @@ +// +// Semaphore_VX.h +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Definition of the SemaphoreImpl class for VxWorks. +// +// Copyright (c) 2004-20011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Semaphore_VX_INCLUDED +#define Foundation_Semaphore_VX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <semLib.h> + + +namespace Poco { + + +class Foundation_API SemaphoreImpl +{ +protected: + SemaphoreImpl(int n, int max); + ~SemaphoreImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + +private: + SEM_ID _sem; +}; + + +// +// inlines +// +inline void SemaphoreImpl::setImpl() +{ + if (semGive(_sem) != OK) + throw SystemException("cannot signal semaphore"); +} + + +} // namespace Poco + + +#endif // Foundation_Semaphore_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Semaphore_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/Semaphore_WIN32.h new file mode 100644 index 0000000000..ac9c31356b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Semaphore_WIN32.h @@ -0,0 +1,58 @@ +// +// Semaphore_WIN32.h +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Definition of the SemaphoreImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Semaphore_WIN32_INCLUDED +#define Foundation_Semaphore_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API SemaphoreImpl +{ +protected: + SemaphoreImpl(int n, int max); + ~SemaphoreImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + +private: + HANDLE _sema; +}; + + +// +// inlines +// +inline void SemaphoreImpl::setImpl() +{ + if (!ReleaseSemaphore(_sema, 1, NULL)) + { + throw SystemException("cannot signal semaphore"); + } +} + + +} // namespace Poco + + +#endif // Foundation_Semaphore_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedLibrary.h b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary.h new file mode 100644 index 0000000000..52292c741e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary.h @@ -0,0 +1,144 @@ +// +// SharedLibrary.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibrary class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedLibrary_INCLUDED +#define Foundation_SharedLibrary_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(hpux) || defined(_hpux) +#include "Poco/SharedLibrary_HPUX.h" +#elif defined(POCO_VXWORKS) +#include "Poco/SharedLibrary_VX.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/SharedLibrary_UNIX.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/SharedLibrary_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/SharedLibrary_WIN32.h" +#endif + + +namespace Poco { + + +class Foundation_API SharedLibrary: private SharedLibraryImpl + /// The SharedLibrary class dynamically + /// loads shared libraries at run-time. +{ +public: + enum Flags + { + SHLIB_GLOBAL = 1, + /// On platforms that use dlopen(), use RTLD_GLOBAL. This is the default + /// if no flags are given. + /// + /// This flag is ignored on platforms that do not use dlopen(). + + SHLIB_LOCAL = 2 + /// On platforms that use dlopen(), use RTLD_LOCAL instead of RTLD_GLOBAL. + /// + /// Note that if this flag is specified, RTTI (including dynamic_cast and throw) will + /// not work for types defined in the shared library with GCC and possibly other + /// compilers as well. See http://gcc.gnu.org/faq.html#dso for more information. + /// + /// This flag is ignored on platforms that do not use dlopen(). + }; + + SharedLibrary(); + /// Creates a SharedLibrary object. + + SharedLibrary(const std::string& path); + /// Creates a SharedLibrary object and loads a library + /// from the given path. + + SharedLibrary(const std::string& path, int flags); + /// Creates a SharedLibrary object and loads a library + /// from the given path, using the given flags. + /// See the Flags enumeration for valid values. + + virtual ~SharedLibrary(); + /// Destroys the SharedLibrary. The actual library + /// remains loaded. + + void load(const std::string& path); + /// Loads a shared library from the given path. + /// Throws a LibraryAlreadyLoadedException if + /// a library has already been loaded. + /// Throws a LibraryLoadException if the library + /// cannot be loaded. + + void load(const std::string& path, int flags); + /// Loads a shared library from the given path, + /// using the given flags. See the Flags enumeration + /// for valid values. + /// Throws a LibraryAlreadyLoadedException if + /// a library has already been loaded. + /// Throws a LibraryLoadException if the library + /// cannot be loaded. + + void unload(); + /// Unloads a shared library. + + bool isLoaded() const; + /// Returns true iff a library has been loaded. + + bool hasSymbol(const std::string& name); + /// Returns true iff the loaded library contains + /// a symbol with the given name. + + void* getSymbol(const std::string& name); + /// Returns the address of the symbol with + /// the given name. For functions, this + /// is the entry point of the function. + /// Throws a NotFoundException if the symbol + /// does not exist. + + const std::string& getPath() const; + /// Returns the path of the library, as + /// specified in a call to load() or the + /// constructor. + + static std::string suffix(); + /// Returns the platform-specific filename suffix + /// for shared libraries (including the period). + /// In debug mode, the suffix also includes a + /// "d" to specify the debug version of a library + /// (e.g., "d.so", "d.dll") unless the library has + /// been compiled with -DPOCO_NO_SHARED_LIBRARY_DEBUG_SUFFIX. + + static bool setSearchPath(const std::string& path); + /// Adds the given path to the list of paths shared libraries + /// are searched in. + /// + /// Returns true if the path was set, otherwise false. + /// + /// Currently only supported on Windows, where it calls + /// SetDllDirectory(). On all other platforms, does not + /// do anything and returns false. + +private: + SharedLibrary(const SharedLibrary&); + SharedLibrary& operator = (const SharedLibrary&); +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_HPUX.h b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_HPUX.h new file mode 100644 index 0000000000..06a6f51bcf --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_HPUX.h @@ -0,0 +1,52 @@ +// +// SharedLibrary_HPUX.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for HP-UX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedLibrary_HPUX_INCLUDED +#define Foundation_SharedLibrary_HPUX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include <dl.h> + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path, int flags); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + static bool setSearchPathImpl(const std::string& path); + +private: + std::string _path; + shl_t _handle; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_HPUX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_UNIX.h b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_UNIX.h new file mode 100644 index 0000000000..1f0c288ad5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_UNIX.h @@ -0,0 +1,57 @@ +// +// SharedLibrary_UNIX.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for UNIX (dlopen). +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedLibrary_UNIX_INCLUDED +#define Foundation_SharedLibrary_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + enum Flags + { + SHLIB_GLOBAL_IMPL = 1, + SHLIB_LOCAL_IMPL = 2 + }; + + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path, int flags); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + static bool setSearchPathImpl(const std::string& path); + +private: + std::string _path; + void* _handle; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_UNIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_VX.h b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_VX.h new file mode 100644 index 0000000000..025118acab --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_VX.h @@ -0,0 +1,52 @@ +// +// SharedLibrary_VX.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for VxWorks. +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedLibrary_VX_INCLUDED +#define Foundation_SharedLibrary_VX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#error #include <moduleLib.h> + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path, int flags); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + static bool setSearchPathImpl(const std::string& path); + +private: + std::string _path; + MODULE_ID _moduleId; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_WIN32.h new file mode 100644 index 0000000000..6b7fc29459 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_WIN32.h @@ -0,0 +1,51 @@ +// +// SharedLibrary_WIN32.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for Win32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedLibrary_WIN32_INCLUDED +#define Foundation_SharedLibrary_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path, int flags); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + static bool setSearchPathImpl(const std::string& path); + +private: + std::string _path; + void* _handle; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_WIN32U.h b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_WIN32U.h new file mode 100644 index 0000000000..3e51c9c95d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedLibrary_WIN32U.h @@ -0,0 +1,51 @@ +// +// SharedLibrary_WIN32U.h +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for Win32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedLibrary_WIN32U_INCLUDED +#define Foundation_SharedLibrary_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path, int flags); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + static bool setSearchPathImpl(const std::string& path); + +private: + std::string _path; + void* _handle; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_WIN32U_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedMemory.h b/contrib/libs/poco/Foundation/include/Poco/SharedMemory.h new file mode 100644 index 0000000000..233856787b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedMemory.h @@ -0,0 +1,113 @@ +// +// SharedMemory.h +// +// Library: Foundation +// Package: Processes +// Module: SharedMemory +// +// Definition of the SharedMemory class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedMemory_INCLUDED +#define Foundation_SharedMemory_INCLUDED + + +#include "Poco/Foundation.h" +#include <algorithm> +#include <cstddef> + + +namespace Poco { + + +class SharedMemoryImpl; +class File; + + +class Foundation_API SharedMemory + /// Create and manage a shared memory object. + /// + /// A SharedMemory object has value semantics, but + /// is implemented using a handle/implementation idiom. + /// Therefore, multiple SharedMemory objects can share + /// a single, reference counted SharedMemoryImpl object. +{ +public: + enum AccessMode + { + AM_READ = 0, + AM_WRITE + }; + + SharedMemory(); + /// Default constructor creates an unmapped SharedMemory object. + /// No clients can connect to an unmapped SharedMemory object. + + SharedMemory(const std::string& name, std::size_t size, AccessMode mode, const void* addrHint = 0, bool server = true); + /// Creates or connects to a shared memory object with the given name. + /// + /// For maximum portability, name should be a valid Unix filename and not + /// contain any slashes or backslashes. + /// + /// An address hint can be passed to the system, specifying the desired + /// start address of the shared memory area. Whether the hint + /// is actually honored is, however, up to the system. Windows platform + /// will generally ignore the hint. + /// + /// If server is set to true, the shared memory region will be unlinked + /// by calling shm_unlink() (on POSIX platforms) when the SharedMemory object is destroyed. + /// The server parameter is ignored on Windows platforms. + + SharedMemory(const File& file, AccessMode mode, const void* addrHint = 0); + /// Maps the entire contents of file into a shared memory segment. + /// + /// An address hint can be passed to the system, specifying the desired + /// start address of the shared memory area. Whether the hint + /// is actually honored is, however, up to the system. Windows platform + /// will generally ignore the hint. + + SharedMemory(const SharedMemory& other); + /// Creates a SharedMemory object by copying another one. + + ~SharedMemory(); + /// Destroys the SharedMemory. + + SharedMemory& operator = (const SharedMemory& other); + /// Assigns another SharedMemory object. + + void swap(SharedMemory& other); + /// Swaps the SharedMemory object with another one. + + char* begin() const; + /// Returns the start address of the shared memory segment. + /// Will be NULL for illegal segments. + + char* end() const; + /// Returns the one-past-end end address of the shared memory segment. + /// Will be NULL for illegal segments. + +private: + SharedMemoryImpl* _pImpl; +}; + + +// +// inlines +// +inline void SharedMemory::swap(SharedMemory& other) +{ + using std::swap; + swap(_pImpl, other._pImpl); +} + + +} // namespace Poco::Poco + + +#endif // Foundation_SharedMemory_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedMemory_DUMMY.h b/contrib/libs/poco/Foundation/include/Poco/SharedMemory_DUMMY.h new file mode 100644 index 0000000000..5a487a0f78 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedMemory_DUMMY.h @@ -0,0 +1,88 @@ +// +// SharedMemoryImpl.h +// +// Library: Foundation +// Package: Processes +// Module: SharedMemoryImpl +// +// Definition of the SharedMemoryImpl class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedMemoryImpl_INCLUDED +#define Foundation_SharedMemoryImpl_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/SharedMemory.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Foundation_API SharedMemoryImpl: public RefCountedObject + /// A dummy implementation of shared memory, for systems + /// that do not have shared memory support. +{ +public: + SharedMemoryImpl(const std::string& id, std::size_t size, SharedMemory::AccessMode mode, const void* addr, bool server); + /// Creates or connects to a shared memory object with the given name. + /// + /// For maximum portability, name should be a valid Unix filename and not + /// contain any slashes or backslashes. + /// + /// An address hint can be passed to the system, specifying the desired + /// start address of the shared memory area. Whether the hint + /// is actually honored is, however, up to the system. Windows platform + /// will generally ignore the hint. + + SharedMemoryImpl(const Poco::File& aFile, SharedMemory::AccessMode mode, const void* addr); + /// Maps the entire contents of file into a shared memory segment. + /// + /// An address hint can be passed to the system, specifying the desired + /// start address of the shared memory area. Whether the hint + /// is actually honored is, however, up to the system. Windows platform + /// will generally ignore the hint. + + char* begin() const; + /// Returns the start address of the shared memory segment. + + char* end() const; + /// Returns the one-past-end end address of the shared memory segment. + +protected: + ~SharedMemoryImpl(); + /// Destroys the SharedMemoryImpl. + +private: + SharedMemoryImpl(); + SharedMemoryImpl(const SharedMemoryImpl&); + SharedMemoryImpl& operator = (const SharedMemoryImpl&); +}; + + +// +// inlines +// +inline char* SharedMemoryImpl::begin() const +{ + return 0; +} + + +inline char* SharedMemoryImpl::end() const +{ + return 0; +} + + +} // namespace Poco + + +#endif // Foundation_SharedMemoryImpl_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedMemory_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/SharedMemory_POSIX.h new file mode 100644 index 0000000000..4ba6ab5e80 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedMemory_POSIX.h @@ -0,0 +1,107 @@ +// +// SharedMemoryImpl.h +// +// Library: Foundation +// Package: Processes +// Module: SharedMemoryImpl +// +// Definition of the SharedMemoryImpl class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedMemoryImpl_INCLUDED +#define Foundation_SharedMemoryImpl_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/SharedMemory.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Foundation_API SharedMemoryImpl: public RefCountedObject + /// Shared memory implementation for POSIX platforms. +{ +public: + SharedMemoryImpl(const std::string& name, std::size_t size, SharedMemory::AccessMode mode, const void* addrHint, bool server); + /// Creates or connects to a shared memory object with the given name. + /// + /// For maximum portability, name should be a valid Unix filename and not + /// contain any slashes or backslashes. + /// + /// An address hint can be passed to the system, specifying the desired + /// start address of the shared memory area. Whether the hint + /// is actually honored is, however, up to the system. Windows platform + /// will generally ignore the hint. + /// + /// If server is set to false, the shared memory region will be unlinked + /// by calling shm_unlink when the SharedMemory object is destroyed. + + SharedMemoryImpl(const Poco::File& file, SharedMemory::AccessMode mode, const void* addrHint); + /// Maps the entire contents of file into a shared memory segment. + /// + /// An address hint can be passed to the system, specifying the desired + /// start address of the shared memory area. Whether the hint + /// is actually honored is, however, up to the system. Windows platform + /// will generally ignore the hint. + + char* begin() const; + /// Returns the start address of the shared memory segment. + + char* end() const; + /// Returns the one-past-end end address of the shared memory segment. + +protected: + void map(const void* addrHint); + /// Maps the shared memory object. + + void unmap(); + /// Unmaps the shared memory object. + + void close(); + /// Releases the handle for the shared memory segment. + + ~SharedMemoryImpl(); + /// Destroys the SharedMemoryImpl. + +private: + SharedMemoryImpl(); + SharedMemoryImpl(const SharedMemoryImpl&); + SharedMemoryImpl& operator = (const SharedMemoryImpl&); + + std::size_t _size; + int _fd; + char* _address; + SharedMemory::AccessMode _access; + std::string _name; + bool _fileMapped; + bool _server; +}; + + +// +// inlines +// +inline char* SharedMemoryImpl::begin() const +{ + return _address; +} + + +inline char* SharedMemoryImpl::end() const +{ + return _address + _size; +} + + +} // namespace Poco + + +#endif // Foundation_SharedMemoryImpl_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedMemory_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/SharedMemory_WIN32.h new file mode 100644 index 0000000000..bd48b6932a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedMemory_WIN32.h @@ -0,0 +1,103 @@ +// +// SharedMemoryImpl.h +// +// Library: Foundation +// Package: Processes +// Module: SharedMemoryImpl +// +// Definition of the SharedMemoryImpl class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedMemoryImpl_INCLUDED +#define Foundation_SharedMemoryImpl_INCLUDED + + +#include "Poco/Poco.h" +#include "Poco/SharedMemory.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Foundation_API SharedMemoryImpl: public RefCountedObject + /// Shared memory implementation for Windows platforms. +{ +public: + SharedMemoryImpl(const std::string& name, std::size_t size, SharedMemory::AccessMode mode, const void* addrHint, bool server); + /// Creates or connects to a shared memory object with the given name. + /// + /// For maximum portability, name should be a valid Unix filename and not + /// contain any slashes or backslashes. + /// + /// An address hint can be passed to the system, specifying the desired + /// start address of the shared memory area. Whether the hint + /// is actually honored is, however, up to the system. Windows platform + /// will generally ignore the hint. + + SharedMemoryImpl(const Poco::File& file, SharedMemory::AccessMode mode, const void* addrHint); + /// Maps the entire contents of file into a shared memory segment. + /// + /// An address hint can be passed to the system, specifying the desired + /// start address of the shared memory area. Whether the hint + /// is actually honored is, however, up to the system. Windows platform + /// will generally ignore the hint. + + char* begin() const; + /// Returns the beginn address of the SharedMemory segment. Will be null for illegal segments. + + char* end() const; + /// Points past the last byte of the end address of the SharedMemory segment. Will be null for illegal segments. + +protected: + void map(); + /// Maps the shared memory object. + + void unmap(); + /// Unmaps the shared memory object. + + void close(); + /// Releases the handle for the shared memory segment. + + ~SharedMemoryImpl(); + /// Destroys the SharedMemoryImpl. + +private: + SharedMemoryImpl(); + SharedMemoryImpl(const SharedMemoryImpl&); + SharedMemoryImpl& operator = (const SharedMemoryImpl&); + + std::string _name; + HANDLE _memHandle; + HANDLE _fileHandle; + DWORD _size; + DWORD _mode; + char* _address; +}; + + +// +// inlines +// +inline char* SharedMemoryImpl::begin() const +{ + return _address; +} + + +inline char* SharedMemoryImpl::end() const +{ + return _address + _size; +} + + +} // namespace Poco + + +#endif // Foundation_SharedMemoryImpl_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SharedPtr.h b/contrib/libs/poco/Foundation/include/Poco/SharedPtr.h new file mode 100644 index 0000000000..899d448839 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SharedPtr.h @@ -0,0 +1,448 @@ +// +// SharedPtr.h +// +// Library: Foundation +// Package: Core +// Module: SharedPtr +// +// Definition of the SharedPtr template class. +// +// Copyright (c) 2005-2008, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SharedPtr_INCLUDED +#define Foundation_SharedPtr_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/AtomicCounter.h" +#include <algorithm> + + +namespace Poco { + + +class ReferenceCounter + /// Simple ReferenceCounter object, does not delete itself when count reaches 0. +{ +public: + ReferenceCounter(): _cnt(1) + { + } + + void duplicate() + { + ++_cnt; + } + + int release() + { + return --_cnt; + } + + int referenceCount() const + { + return _cnt.value(); + } + +private: + AtomicCounter _cnt; +}; + + +template <class C> +class ReleasePolicy + /// The default release policy for SharedPtr, which + /// simply uses the delete operator to delete an object. +{ +public: + static void release(C* pObj) + /// Delete the object. + /// Note that pObj can be 0. + { + delete pObj; + } +}; + + +template <class C> +class ReleaseArrayPolicy + /// The release policy for SharedPtr holding arrays. +{ +public: + static void release(C* pObj) + /// Delete the object. + /// Note that pObj can be 0. + { + delete [] pObj; + } +}; + + +template <class C, class RC = ReferenceCounter, class RP = ReleasePolicy<C> > +class SharedPtr + /// SharedPtr is a "smart" pointer for classes implementing + /// reference counting based garbage collection. + /// SharedPtr is thus similar to AutoPtr. Unlike the + /// AutoPtr template, which can only be used with + /// classes that support reference counting, SharedPtr + /// can be used with any class. For this to work, a + /// SharedPtr manages a reference count for the object + /// it manages. + /// + /// SharedPtr works in the following way: + /// If an SharedPtr is assigned an ordinary pointer to + /// an object (via the constructor or the assignment operator), + /// it takes ownership of the object and the object's reference + /// count is initialized to one. + /// If the SharedPtr is assigned another SharedPtr, the + /// object's reference count is incremented by one. + /// The destructor of SharedPtr decrements the object's + /// reference count by one and deletes the object if the + /// reference count reaches zero. + /// SharedPtr supports dereferencing with both the -> + /// and the * operator. An attempt to dereference a null + /// SharedPtr results in a NullPointerException being thrown. + /// SharedPtr also implements all relational operators and + /// a cast operator in case dynamic casting of the encapsulated data types + /// is required. +{ +public: + SharedPtr(): _pCounter(new RC), _ptr(0) + { + } + + SharedPtr(C* ptr) + try: + _pCounter(new RC), + _ptr(ptr) + { + } + catch (...) + { + RP::release(ptr); + } + + template <class Other, class OtherRP> + SharedPtr(const SharedPtr<Other, RC, OtherRP>& ptr): _pCounter(ptr._pCounter), _ptr(const_cast<Other*>(ptr.get())) + { + _pCounter->duplicate(); + } + + SharedPtr(const SharedPtr& ptr): _pCounter(ptr._pCounter), _ptr(ptr._ptr) + { + _pCounter->duplicate(); + } + + ~SharedPtr() + { + try + { + release(); + } + catch (...) + { + poco_unexpected(); + } + } + + SharedPtr& assign(C* ptr) + { + if (get() != ptr) + { + SharedPtr tmp(ptr); + swap(tmp); + } + return *this; + } + + SharedPtr& assign(const SharedPtr& ptr) + { + if (&ptr != this) + { + SharedPtr tmp(ptr); + swap(tmp); + } + return *this; + } + + template <class Other, class OtherRP> + SharedPtr& assign(const SharedPtr<Other, RC, OtherRP>& ptr) + { + if (ptr.get() != _ptr) + { + SharedPtr tmp(ptr); + swap(tmp); + } + return *this; + } + + void reset() + { + assign(0); + } + + void reset(C* ptr) + { + assign(ptr); + } + + void reset(const SharedPtr& ptr) + { + assign(ptr); + } + + template <class Other, class OtherRP> + void reset(const SharedPtr<Other, RC, OtherRP>& ptr) + { + assign<Other, OtherRP>(ptr); + } + + SharedPtr& operator = (C* ptr) + { + return assign(ptr); + } + + SharedPtr& operator = (const SharedPtr& ptr) + { + return assign(ptr); + } + + template <class Other, class OtherRP> + SharedPtr& operator = (const SharedPtr<Other, RC, OtherRP>& ptr) + { + return assign<Other>(ptr); + } + + void swap(SharedPtr& ptr) + { + std::swap(_ptr, ptr._ptr); + std::swap(_pCounter, ptr._pCounter); + } + + template <class Other> + SharedPtr<Other, RC, RP> cast() const + /// Casts the SharedPtr via a dynamic cast to the given type. + /// Returns an SharedPtr containing NULL if the cast fails. + /// Example: (assume class Sub: public Super) + /// SharedPtr<Super> super(new Sub()); + /// SharedPtr<Sub> sub = super.cast<Sub>(); + /// poco_assert (sub.get()); + { + Other* pOther = dynamic_cast<Other*>(_ptr); + if (pOther) + return SharedPtr<Other, RC, RP>(_pCounter, pOther); + return SharedPtr<Other, RC, RP>(); + } + + template <class Other> + SharedPtr<Other, RC, RP> unsafeCast() const + /// Casts the SharedPtr via a static cast to the given type. + /// Example: (assume class Sub: public Super) + /// SharedPtr<Super> super(new Sub()); + /// SharedPtr<Sub> sub = super.unsafeCast<Sub>(); + /// poco_assert (sub.get()); + { + Other* pOther = static_cast<Other*>(_ptr); + return SharedPtr<Other, RC, RP>(_pCounter, pOther); + } + + C* operator -> () + { + return deref(); + } + + const C* operator -> () const + { + return deref(); + } + + C& operator * () + { + return *deref(); + } + + const C& operator * () const + { + return *deref(); + } + + C* get() + { + return _ptr; + } + + const C* get() const + { + return _ptr; + } + + operator C* () + { + return _ptr; + } + + operator const C* () const + { + return _ptr; + } + + bool operator ! () const + { + return _ptr == 0; + } + + bool isNull() const + { + return _ptr == 0; + } + + bool operator == (const SharedPtr& ptr) const + { + return get() == ptr.get(); + } + + bool operator == (const C* ptr) const + { + return get() == ptr; + } + + bool operator == (C* ptr) const + { + return get() == ptr; + } + + bool operator != (const SharedPtr& ptr) const + { + return get() != ptr.get(); + } + + bool operator != (const C* ptr) const + { + return get() != ptr; + } + + bool operator != (C* ptr) const + { + return get() != ptr; + } + + bool operator < (const SharedPtr& ptr) const + { + return get() < ptr.get(); + } + + bool operator < (const C* ptr) const + { + return get() < ptr; + } + + bool operator < (C* ptr) const + { + return get() < ptr; + } + + bool operator <= (const SharedPtr& ptr) const + { + return get() <= ptr.get(); + } + + bool operator <= (const C* ptr) const + { + return get() <= ptr; + } + + bool operator <= (C* ptr) const + { + return get() <= ptr; + } + + bool operator > (const SharedPtr& ptr) const + { + return get() > ptr.get(); + } + + bool operator > (const C* ptr) const + { + return get() > ptr; + } + + bool operator > (C* ptr) const + { + return get() > ptr; + } + + bool operator >= (const SharedPtr& ptr) const + { + return get() >= ptr.get(); + } + + bool operator >= (const C* ptr) const + { + return get() >= ptr; + } + + bool operator >= (C* ptr) const + { + return get() >= ptr; + } + + int referenceCount() const + { + return _pCounter->referenceCount(); + } + +private: + C* deref() const + { + if (!_ptr) + throw NullPointerException(); + + return _ptr; + } + + void release() + { + poco_assert_dbg (_pCounter); + int i = _pCounter->release(); + if (i == 0) + { + RP::release(_ptr); + _ptr = 0; + + delete _pCounter; + _pCounter = 0; + } + } + + SharedPtr(RC* pCounter, C* ptr): _pCounter(pCounter), _ptr(ptr) + /// for cast operation + { + poco_assert_dbg (_pCounter); + _pCounter->duplicate(); + } + +private: + RC* _pCounter; + C* _ptr; + + template <class OtherC, class OtherRC, class OtherRP> friend class SharedPtr; +}; + + +template <class C, class RC, class RP> +inline void swap(SharedPtr<C, RC, RP>& p1, SharedPtr<C, RC, RP>& p2) +{ + p1.swap(p2); +} + + +} // namespace Poco + + +#endif // Foundation_SharedPtr_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SignalHandler.h b/contrib/libs/poco/Foundation/include/Poco/SignalHandler.h new file mode 100644 index 0000000000..22b5f16734 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SignalHandler.h @@ -0,0 +1,129 @@ +// +// SignalHandler.h +// +// Library: Foundation +// Package: Threading +// Module: SignalHandler +// +// Definition of the SignalHandler class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SignalHandler_INCLUDED +#define Foundation_SignalHandler_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) + + +#include <vector> +#include <setjmp.h> + + +namespace Poco { + + +class Foundation_API SignalHandler + /// This helper class simplifies the handling of POSIX signals. + /// + /// The class provides a signal handler (installed with + /// installHandlers()) that translates certain POSIX + /// signals (SIGILL, SIGBUS, SIGSEGV, SIGSYS) into + /// C++ exceptions. + /// + /// Internally, a stack of sigjmp_buf structs is maintained for + /// each thread. The constructor pushes a new sigjmp_buf onto + /// the current thread's stack. The destructor pops the sigjmp_buf + /// from the stack. + /// + /// The poco_throw_on_signal macro creates an instance of SignalHandler + /// on the stack, which results in a new sigjmp_buf being created. + /// The sigjmp_buf is then set-up with sigsetjmp(). + /// + /// The handleSignal() method, which is invoked when a signal arrives, + /// checks if a sigjmp_buf is available for the current thread. + /// If so, siglongjmp() is used to jump out of the signal handler. + /// + /// Typical usage is as follows: + /// + /// try + /// { + /// poco_throw_on_signal; + /// ... + /// } + /// catch (Poco::SignalException&) + /// { + /// ... + /// } + /// + /// The best way to deal with a SignalException is to log as much context + /// information as possible, to aid in debugging, and then to exit. + /// + /// The SignalHandler can be disabled globally by compiling POCO and client + /// code with the POCO_NO_SIGNAL_HANDLER macro defined. +{ +public: + SignalHandler(); + /// Creates the SignalHandler. + + ~SignalHandler(); + /// Destroys the SignalHandler. + + sigjmp_buf& jumpBuffer(); + /// Returns the top-most sigjmp_buf for the current thread. + + static void throwSignalException(int sig); + /// Throws a SignalException with a textual description + /// of the given signal as argument. + + static void install(); + /// Installs signal handlers for SIGILL, SIGBUS, SIGSEGV + /// and SIGSYS. + +protected: + static void handleSignal(int sig); + /// The actual signal handler. + + struct JumpBuffer + /// sigjmp_buf cannot be used to instantiate a std::vector, + /// so we provide a wrapper struct. + { + sigjmp_buf buf; + }; + typedef std::vector<JumpBuffer> JumpBufferVec; + + static JumpBufferVec& jumpBufferVec(); + /// Returns the JumpBufferVec for the current thread. + +private: + static JumpBufferVec _jumpBufferVec; + + friend class ThreadImpl; +}; + + +#ifndef POCO_NO_SIGNAL_HANDLER +#define poco_throw_on_signal \ + Poco::SignalHandler _poco_signalHandler; \ + int _poco_signal = sigsetjmp(_poco_signalHandler.jumpBuffer(), 1); \ + if (_poco_signal) _poco_signalHandler.throwSignalException(_poco_signal); +#else +#define poco_throw_on_signal +#endif + + +} // namespace Poco + + +#endif // POCO_OS_FAMILY_UNIX + + +#endif // Foundation_SignalHandler_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SimpleFileChannel.h b/contrib/libs/poco/Foundation/include/Poco/SimpleFileChannel.h new file mode 100644 index 0000000000..29882f45b5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SimpleFileChannel.h @@ -0,0 +1,150 @@ +// +// SimpleFileChannel.h +// +// Library: Foundation +// Package: Logging +// Module: SimpleFileChannel +// +// Definition of the SimpleFileChannel class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SimpleFileChannel_INCLUDED +#define Foundation_SimpleFileChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Timestamp.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class LogFile; + + +class Foundation_API SimpleFileChannel: public Channel + /// A Channel that writes to a file. This class only + /// supports simple log file rotation. + /// + /// For more features, see the FileChannel class. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is in the text. + /// + /// Log file rotation based on log file size is supported. + /// + /// If rotation is enabled, the SimpleFileChannel will + /// alternate between two log files. If the size of + /// the primary log file exceeds a specified limit, + /// the secondary log file will be used, and vice + /// versa. + /// + /// Log rotation is configured with the "rotation" + /// property, which supports the following values: + /// * never: no log rotation + /// * <n>: the file is rotated when its size exceeds + /// <n> bytes. + /// * <n> K: the file is rotated when its size exceeds + /// <n> Kilobytes. + /// * <n> M: the file is rotated when its size exceeds + /// <n> Megabytes. + /// + /// The path of the (primary) log file can be specified with + /// the "path" property. Optionally, the path of the secondary + /// log file can be specified with the "secondaryPath" property. + /// + /// If no secondary path is specified, the secondary path will + /// default to <primaryPath>.1. + /// + /// The flush property specifies whether each log message is flushed + /// immediately to the log file (which may hurt application performance, + /// but ensures that everything is in the log in case of a system crash), + // or whether it's allowed to stay in the system's file buffer for some time. + /// Valid values are: + /// + /// * true: Every essages is immediately flushed to the log file (default). + /// * false: Messages are not immediately flushed to the log file. + /// +{ +public: + SimpleFileChannel(); + /// Creates the FileChannel. + + SimpleFileChannel(const std::string& path); + /// Creates the FileChannel for a file with the given path. + + void open(); + /// Opens the FileChannel and creates the log file if necessary. + + void close(); + /// Closes the FileChannel. + + void log(const Message& msg); + /// Logs the given message to the file. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name. + /// + /// The following properties are supported: + /// * path: The primary log file's path. + /// * secondaryPath: The secondary log file's path. + /// * rotation: The log file's rotation mode. See the + /// SimpleFileChannel class for details. + /// * flush: Specifies whether messages are immediately + /// flushed to the log file. See the SimpleFileChannel + /// class for details. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + /// See setProperty() for a description of the supported + /// properties. + + Timestamp creationDate() const; + /// Returns the log file's creation date. + + UInt64 size() const; + /// Returns the log file's current size in bytes. + + const std::string& path() const; + /// Returns the log file's primary path. + + const std::string& secondaryPath() const; + /// Returns the log file's secondary path. + + static const std::string PROP_PATH; + static const std::string PROP_SECONDARYPATH; + static const std::string PROP_ROTATION; + static const std::string PROP_FLUSH; + +protected: + ~SimpleFileChannel(); + void setRotation(const std::string& rotation); + void setFlush(const std::string& flush); + void rotate(); + +private: + std::string _path; + std::string _secondaryPath; + std::string _rotation; + UInt64 _limit; + bool _flush; + LogFile* _pFile; + FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SimpleFileChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SimpleHashTable.h b/contrib/libs/poco/Foundation/include/Poco/SimpleHashTable.h new file mode 100644 index 0000000000..c149cd6b7e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SimpleHashTable.h @@ -0,0 +1,398 @@ +// +// SimpleHashTable.h +// +// Library: Foundation +// Package: Hashing +// Module: SimpleHashTable +// +// Definition of the SimpleHashTable class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SimpleHashTable_INCLUDED +#define Foundation_SimpleHashTable_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/HashFunction.h" +#include "Poco/HashStatistic.h" +#include <vector> +#include <map> +#include <cstddef> +#include <algorithm> + + +namespace Poco { + + +//@ deprecated +template <class Key, class Value, class KeyHashFunction = HashFunction<Key> > +class SimpleHashTable + /// A SimpleHashTable stores a key value pair that can be looked up via a hashed key. + /// + /// In comparision to a HashTable, this class handles collisions by sequentially searching the next + /// free location. This also means that the maximum size of this table is limited, i.e. if the hash table + /// is full, it will throw an exception and that this class does not support remove operations. + /// On the plus side it is faster than the HashTable. + /// + /// This class is NOT thread safe. +{ +public: + class HashEntry + { + public: + Key key; + Value value; + HashEntry(const Key k, const Value v): key(k), value(v) + { + } + }; + + typedef std::vector<HashEntry*> HashTableVector; + + SimpleHashTable(UInt32 capacity = 251): _entries(capacity, 0), _size(0), _capacity(capacity) + /// Creates the SimpleHashTable. + { + } + + SimpleHashTable(const SimpleHashTable& ht): + _size(ht._size), + _capacity(ht._capacity) + { + _entries.reserve(ht._capacity); + for (typename HashTableVector::iterator it = ht._entries.begin(); it != ht._entries.end(); ++it) + { + if (*it) + _entries.push_back(new HashEntry(*it)); + else + _entries.push_back(0); + } + } + + ~SimpleHashTable() + /// Destroys the SimpleHashTable. + { + clear(); + } + + SimpleHashTable& operator = (const SimpleHashTable& ht) + { + if (this != &ht) + { + SimpleHashTable tmp(ht); + swap(tmp); + } + return *this; + } + + void swap(SimpleHashTable& ht) + { + using std::swap; + swap(_entries, ht._entries); + swap(_size, ht._size); + swap(_capacity, ht._capacity); + } + + void clear() + { + for (typename HashTableVector::iterator it = _entries.begin(); it != _entries.end(); ++it) + { + delete *it; + *it = 0; + } + _size = 0; + } + + UInt32 insert(const Key& key, const Value& value) + /// Returns the hash value of the inserted item. + /// Throws an exception if the entry was already inserted + { + UInt32 hsh = hash(key); + insertRaw(key, hsh, value); + return hsh; + } + + Value& insertRaw(const Key& key, UInt32 hsh, const Value& value) + /// Returns the hash value of the inserted item. + /// Throws an exception if the entry was already inserted + { + UInt32 pos = hsh; + if (!_entries[pos]) + _entries[pos] = new HashEntry(key, value); + else + { + UInt32 origHash = hsh; + while (_entries[hsh % _capacity]) + { + if (_entries[hsh % _capacity]->key == key) + throw ExistsException(); + if (hsh - origHash > _capacity) + throw PoolOverflowException("SimpleHashTable full"); + hsh++; + } + pos = hsh % _capacity; + _entries[pos] = new HashEntry(key, value); + } + _size++; + return _entries[pos]->value; + } + + UInt32 update(const Key& key, const Value& value) + /// Returns the hash value of the inserted item. + /// Replaces an existing entry if it finds one + { + UInt32 hsh = hash(key); + updateRaw(key, hsh, value); + return hsh; + } + + void updateRaw(const Key& key, UInt32 hsh, const Value& value) + /// Returns the hash value of the inserted item. + /// Replaces an existing entry if it finds one + { + if (!_entries[hsh]) + _entries[hsh] = new HashEntry(key, value); + else + { + UInt32 origHash = hsh; + while (_entries[hsh % _capacity]) + { + if (_entries[hsh % _capacity]->key == key) + { + _entries[hsh % _capacity]->value = value; + return; + } + if (hsh - origHash > _capacity) + throw PoolOverflowException("SimpleHashTable full"); + hsh++; + } + _entries[hsh % _capacity] = new HashEntry(key, value); + } + _size++; + } + + UInt32 hash(const Key& key) const + { + return _hash(key, _capacity); + } + + const Value& get(const Key& key) const + /// Throws an exception if the value does not exist + { + UInt32 hsh = hash(key); + return getRaw(key, hsh); + } + + const Value& getRaw(const Key& key, UInt32 hsh) const + /// Throws an exception if the value does not exist + { + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _capacity]) + { + if (_entries[hsh % _capacity]->key == key) + { + return _entries[hsh % _capacity]->value; + } + } + else + throw InvalidArgumentException("value not found"); + if (hsh - origHash > _capacity) + throw InvalidArgumentException("value not found"); + hsh++; + } + } + + Value& get(const Key& key) + /// Throws an exception if the value does not exist + { + UInt32 hsh = hash(key); + return const_cast<Value&>(getRaw(key, hsh)); + } + + const Value& operator [] (const Key& key) const + { + return get(key); + } + + Value& operator [] (const Key& key) + { + UInt32 hsh = hash(key); + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _capacity]) + { + if (_entries[hsh % _capacity]->key == key) + { + return _entries[hsh % _capacity]->value; + } + } + else return insertRaw(key, hsh, Value()); + if (hsh - origHash > _capacity) + return insertRaw(key, hsh, Value()); + hsh++; + } + } + + const Key& getKeyRaw(const Key& key, UInt32 hsh) + /// Throws an exception if the key does not exist. returns a reference to the internally + /// stored key. Useful when someone does an insert and wants for performance reason only to store + /// a pointer to the key in another collection + { + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _capacity]) + { + if (_entries[hsh % _capacity]->key == key) + { + return _entries[hsh % _capacity]->key; + } + } + else + throw InvalidArgumentException("key not found"); + + if (hsh - origHash > _capacity) + throw InvalidArgumentException("key not found"); + hsh++; + } + } + + bool get(const Key& key, Value& v) const + /// Sets v to the found value, returns false if no value was found + { + UInt32 hsh = hash(key); + return getRaw(key, hsh, v); + } + + bool getRaw(const Key& key, UInt32 hsh, Value& v) const + /// Sets v to the found value, returns false if no value was found + { + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _capacity]) + { + if (_entries[hsh % _capacity]->key == key) + { + v = _entries[hsh % _capacity]->value; + return true; + } + } + else + return false; + if (hsh - origHash > _capacity) + return false; + hsh++; + } + } + + bool exists(const Key& key) const + { + UInt32 hsh = hash(key); + return existsRaw(key, hsh); + } + + bool existsRaw(const Key& key, UInt32 hsh) const + { + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _capacity]) + { + if (_entries[hsh % _capacity]->key == key) + { + return true; + } + } + else + return false; + if (hsh - origHash > _capacity) + return false; + hsh++; + } + } + + std::size_t size() const + /// Returns the number of elements already inserted into the SimpleHashTable + { + return _size; + } + + UInt32 capacity() const + { + return _capacity; + } + + void resize(UInt32 newSize) + /// Resizes the hashtable, rehashes all existing entries. Expensive! + { + if (_capacity != newSize) + { + SimpleHashTable tmp(newSize); + swap(tmp); + for (typename HashTableVector::const_iterator it = tmp._entries.begin(); it != tmp._entries.end(); ++it) + { + if (*it) + { + insertRaw((*it)->key, hash((*it)->key), (*it)->value); + } + } + } + } + + HashStatistic currentState(bool details = false) const + /// Returns the current internal state + { + UInt32 numberOfEntries = (UInt32)_size; + UInt32 numZeroEntries = 0; + UInt32 maxEntriesPerHash = 0; + std::vector<UInt32> detailedEntriesPerHash; + #ifdef _DEBUG + UInt32 totalSize = 0; + #endif + for (int i=0; i < _capacity; ++i) + { + if (_entries[i]) + { + maxEntriesPerHash = 1; + UInt32 size = 1; + if (details) + detailedEntriesPerHash.push_back(size); + #ifdef _DEBUG + totalSize += size; + #endif + } + else + { + numZeroEntries++; + if (details) + detailedEntriesPerHash.push_back(0); + } + } + #ifdef _DEBUG + poco_assert_dbg(totalSize == numberOfEntries); + #endif + return HashStatistic(_capacity, numberOfEntries, numZeroEntries, maxEntriesPerHash, detailedEntriesPerHash); + } + +private: + HashTableVector _entries; + std::size_t _size; + UInt32 _capacity; + KeyHashFunction _hash; +}; + + +} // namespace Poco + + +#endif // Foundation_HashTable_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SingletonHolder.h b/contrib/libs/poco/Foundation/include/Poco/SingletonHolder.h new file mode 100644 index 0000000000..8735f114b5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SingletonHolder.h @@ -0,0 +1,77 @@ +// +// SingletonHolder.h +// +// Library: Foundation +// Package: Core +// Module: SingletonHolder +// +// Definition of the SingletonHolder template. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SingletonHolder_INCLUDED +#define Foundation_SingletonHolder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template <class S> +class SingletonHolder + /// This is a helper template class for managing + /// singleton objects allocated on the heap. + /// The class ensures proper deletion (including + /// calling of the destructor) of singleton objects + /// when the application that created them terminates. +{ +public: + SingletonHolder(): + _pS(0) + /// Creates the SingletonHolder. + { + } + + ~SingletonHolder() + /// Destroys the SingletonHolder and the singleton + /// object that it holds. + { + delete _pS; + } + + S* get() + /// Returns a pointer to the singleton object + /// hold by the SingletonHolder. The first call + /// to get will create the singleton. + { + FastMutex::ScopedLock lock(_m); + if (!_pS) _pS = new S; + return _pS; + } + + void reset() + /// Deletes the singleton object. + { + FastMutex::ScopedLock lock(_m); + delete _pS; + _pS = 0; + } + +private: + S* _pS; + FastMutex _m; +}; + + +} // namespace Poco + + +#endif // Foundation_SingletonHolder_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SortedDirectoryIterator.h b/contrib/libs/poco/Foundation/include/Poco/SortedDirectoryIterator.h new file mode 100644 index 0000000000..94c822be41 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SortedDirectoryIterator.h @@ -0,0 +1,70 @@ +// +// SortedDirectoryIterator.h +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the SortedDirectoryIterator class. +// +// Copyright (c) 2004-2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SortedDirectoryIterator_INCLUDED +#define Foundation_SortedDirectoryIterator_INCLUDED + +#include "Poco/Foundation.h" +#include "Poco/File.h" +#include "Poco/Path.h" +#include "Poco/DirectoryIterator.h" +#include <deque> + + +namespace Poco +{ + +class Foundation_API SortedDirectoryIterator: public DirectoryIterator + /// The SortedDirectoryIterator class is similar to + /// DirectoryIterator class, but places directories before files + /// and sorts content alphabetically. +{ +public: + SortedDirectoryIterator(); + /// Creates the end iterator. + + SortedDirectoryIterator(const std::string& path); + /// Creates a directory iterator for the given path. + + SortedDirectoryIterator(const DirectoryIterator& iterator); + /// Creates a directory iterator for the given path. + + SortedDirectoryIterator(const File& file); + /// Creates a directory iterator for the given file. + + SortedDirectoryIterator(const Path& path); + /// Creates a directory iterator for the given path. + + virtual ~SortedDirectoryIterator(); + /// Destroys the DirsFirstDirectoryIterator. + + virtual SortedDirectoryIterator& operator ++(); // prefix + +private: + bool _is_finished; + std::deque<std::string> _directories; + std::deque<std::string> _files; + + void next(); + /// Take next item + void scan(); + /// Scan directory to collect its children directories and files +}; + + +} // namespace Poco + +#endif //Foundation_SortedDirectoryIterator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SplitterChannel.h b/contrib/libs/poco/Foundation/include/Poco/SplitterChannel.h new file mode 100644 index 0000000000..75aa33b20a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SplitterChannel.h @@ -0,0 +1,77 @@ +// +// SplitterChannel.h +// +// Library: Foundation +// Package: Logging +// Module: SplitterChannel +// +// Definition of the SplitterChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SplitterChannel_INCLUDED +#define Foundation_SplitterChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Mutex.h" +#include <vector> + + +namespace Poco { + + +class Foundation_API SplitterChannel: public Channel + /// This channel sends a message to multiple + /// channels simultaneously. +{ +public: + SplitterChannel(); + /// Creates the SplitterChannel. + + void addChannel(Channel* pChannel); + /// Attaches a channel, which may not be null. + + void removeChannel(Channel* pChannel); + /// Removes a channel. + + void log(const Message& msg); + /// Sends the given Message to all + /// attaches channels. + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// Only the "channel" property is supported, which allows + /// adding a comma-separated list of channels via the LoggingRegistry. + /// The "channel" property is set-only. + /// To simplify file-based configuration, all property + /// names starting with "channel" are treated as "channel". + + void close(); + /// Removes all channels. + + int count() const; + /// Returns the number of channels in the SplitterChannel. + +protected: + ~SplitterChannel(); + +private: + typedef std::vector<Channel*> ChannelVec; + + ChannelVec _channels; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SplitterChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Stopwatch.h b/contrib/libs/poco/Foundation/include/Poco/Stopwatch.h new file mode 100644 index 0000000000..6bc27fc92b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Stopwatch.h @@ -0,0 +1,108 @@ +// +// Stopwatch.h +// +// Library: Foundation +// Package: DateTime +// Module: Stopwatch +// +// Definition of the Stopwatch class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Stopwatch_INCLUDED +#define Foundation_Stopwatch_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Clock.h" + + +namespace Poco { + + +class Foundation_API Stopwatch + /// A simple facility to measure time intervals + /// with microsecond resolution. +{ +public: + Stopwatch(); + ~Stopwatch(); + + void start(); + /// Starts (or restarts) the stopwatch. + + void stop(); + /// Stops or pauses the stopwatch. + + void reset(); + /// Resets the stopwatch. + + void restart(); + /// Resets and starts the stopwatch. + + Clock::ClockDiff elapsed() const; + /// Returns the elapsed time in microseconds + /// since the stopwatch started. + + int elapsedSeconds() const; + /// Returns the number of seconds elapsed + /// since the stopwatch started. + + static Clock::ClockVal resolution(); + /// Returns the resolution of the stopwatch. + +private: + Stopwatch(const Stopwatch&); + Stopwatch& operator = (const Stopwatch&); + + Clock _start; + Clock::ClockDiff _elapsed; + bool _running; +}; + + +// +// inlines +// +inline void Stopwatch::start() +{ + if (!_running) + { + _start.update(); + _running = true; + } +} + + +inline void Stopwatch::stop() +{ + if (_running) + { + Clock current; + _elapsed += current - _start; + _running = false; + } +} + + +inline int Stopwatch::elapsedSeconds() const +{ + return int(elapsed()/resolution()); +} + + +inline Clock::ClockVal Stopwatch::resolution() +{ + return Clock::resolution(); +} + + +} // namespace Poco + + +#endif // Foundation_Stopwatch_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/StrategyCollection.h b/contrib/libs/poco/Foundation/include/Poco/StrategyCollection.h new file mode 100644 index 0000000000..6372d46620 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/StrategyCollection.h @@ -0,0 +1,133 @@ +// +// StrategyCollection.h +// +// Library: Foundation +// Package: Cache +// Module: StrategyCollection +// +// Definition of the StrategyCollection class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_StrategyCollection_INCLUDED +#define Foundation_StrategyCollection_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/AbstractStrategy.h" +#include "Poco/SharedPtr.h" +#include <vector> + + +namespace Poco { + + +template <class TKey, class TValue> +class StrategyCollection: public AbstractStrategy<TKey, TValue> + /// An StrategyCollection is a decorator masking n collections as a single one. +{ +public: + typedef std::vector<SharedPtr<AbstractStrategy<TKey, TValue> > > Strategies; + typedef typename Strategies::iterator Iterator; + typedef typename Strategies::const_iterator ConstIterator; + +public: + StrategyCollection() + { + } + + ~StrategyCollection() + { + } + + void pushBack(AbstractStrategy<TKey, TValue>* pStrat) + /// Adds an AbstractStrategy to the collection. Class takes ownership of pointer + { + _strategies.push_back(SharedPtr<AbstractStrategy<TKey, TValue> >(pStrat)); + } + + void popBack() + /// Removes the last added AbstractStrategy from the collection. + { + _strategies.pop_back(); + } + + void onAdd(const void* pSender, const KeyValueArgs <TKey, TValue>& key) + /// Adds the key to the strategy. + /// If for the key already an entry exists, it will be overwritten. + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onAdd(pSender, key); + } + } + + void onRemove(const void* pSender, const TKey& key) + /// Removes an entry from the strategy. If the entry is not found + /// the remove is ignored. + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onRemove(pSender, key); + } + } + + void onGet(const void* pSender, const TKey& key) + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onGet(pSender, key); + } + } + + void onClear(const void* pSender, const EventArgs& args) + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onClear(pSender, args); + } + } + + void onIsValid(const void* pSender, ValidArgs<TKey>& key) + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt && key.isValid(); ++it) + { + (*it)->onIsValid(pSender, key); + } + } + + void onReplace(const void* pSender, std::set<TKey>& elemsToRemove) + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onReplace(pSender, elemsToRemove); + } + } + +protected: + Strategies _strategies; +}; + + +} // namespace Poco + + +#endif // Foundation_StrategyCollection_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/StreamChannel.h b/contrib/libs/poco/Foundation/include/Poco/StreamChannel.h new file mode 100644 index 0000000000..8ecf50a773 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/StreamChannel.h @@ -0,0 +1,59 @@ +// +// StreamChannel.h +// +// Library: Foundation +// Package: Logging +// Module: StreamChannel +// +// Definition of the StreamChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_StreamChannel_INCLUDED +#define Foundation_StreamChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Mutex.h" +#include <ostream> + + +namespace Poco { + + +class Foundation_API StreamChannel: public Channel + /// A channel that writes to an ostream. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is contained + /// in the text. +{ +public: + StreamChannel(std::ostream& str); + /// Creates the channel. + + void log(const Message& msg); + /// Logs the given message to the channel's stream. + +protected: + virtual ~StreamChannel(); + +private: + std::ostream& _str; + FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_StreamChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/StreamConverter.h b/contrib/libs/poco/Foundation/include/Poco/StreamConverter.h new file mode 100644 index 0000000000..c880e2632f --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/StreamConverter.h @@ -0,0 +1,128 @@ +// +// StreamConverter.h +// +// Library: Foundation +// Package: Text +// Module: StreamConverter +// +// Definition of the StreamConverter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_StreamConverter_INCLUDED +#define Foundation_StreamConverter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API StreamConverterBuf: public UnbufferedStreamBuf + /// A StreamConverter converts streams from one encoding (inEncoding) + /// into another (outEncoding). + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// If a byte sequence is not valid in inEncoding, defaultChar is used + /// instead and the encoding error count is incremented. +{ +public: + StreamConverterBuf(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the StreamConverterBuf and connects it + /// to the given input stream. + + StreamConverterBuf(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the StreamConverterBuf and connects it + /// to the given output stream. + + ~StreamConverterBuf(); + /// Destroys the StreamConverterBuf. + + int errors() const; + /// Returns the number of encoding errors encountered. + +protected: + int readFromDevice(); + int writeToDevice(char c); + +private: + std::istream* _pIstr; + std::ostream* _pOstr; + const TextEncoding& _inEncoding; + const TextEncoding& _outEncoding; + int _defaultChar; + unsigned char _buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; + int _sequenceLength; + int _pos; + int _errors; +}; + + +class Foundation_API StreamConverterIOS: public virtual std::ios + /// The base class for InputStreamConverter and OutputStreamConverter. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + StreamConverterIOS(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + StreamConverterIOS(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + ~StreamConverterIOS(); + StreamConverterBuf* rdbuf(); + int errors() const; + +protected: + StreamConverterBuf _buf; +}; + + +class Foundation_API InputStreamConverter: public StreamConverterIOS, public std::istream + /// This stream converts all characters read from the + /// underlying istream from one character encoding into another. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// If a byte sequence read from the underlying stream is not valid in inEncoding, + /// defaultChar is used instead and the encoding error count is incremented. +{ +public: + InputStreamConverter(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the InputStreamConverter and connects it + /// to the given input stream. + + ~InputStreamConverter(); + /// Destroys the stream. +}; + + +class Foundation_API OutputStreamConverter: public StreamConverterIOS, public std::ostream + /// This stream converts all characters written to the + /// underlying ostream from one character encoding into another. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// If a byte sequence written to the stream is not valid in inEncoding, + /// defaultChar is used instead and the encoding error count is incremented. +{ +public: + OutputStreamConverter(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the OutputStreamConverter and connects it + /// to the given input stream. + + ~OutputStreamConverter(); + /// Destroys the CountingOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_StreamConverter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/StreamCopier.h b/contrib/libs/poco/Foundation/include/Poco/StreamCopier.h new file mode 100644 index 0000000000..fda660c43c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/StreamCopier.h @@ -0,0 +1,85 @@ +// +// StreamCopier.h +// +// Library: Foundation +// Package: Streams +// Module: StreamCopier +// +// Definition of class StreamCopier. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_StreamCopier_INCLUDED +#define Foundation_StreamCopier_INCLUDED + + +#include "Poco/Foundation.h" +#include <istream> +#include <ostream> +#include <cstddef> + + +namespace Poco { + + +class Foundation_API StreamCopier + /// This class provides static methods to copy the contents from one stream + /// into another. +{ +public: + static std::streamsize copyStream(std::istream& istr, std::ostream& ostr, std::size_t bufferSize = 8192); + /// Writes all bytes readable from istr to ostr, using an internal buffer. + /// + /// Returns the number of bytes copied. + +#if defined(POCO_HAVE_INT64) + static Poco::UInt64 copyStream64(std::istream& istr, std::ostream& ostr, std::size_t bufferSize = 8192); + /// Writes all bytes readable from istr to ostr, using an internal buffer. + /// + /// Returns the number of bytes copied as a 64-bit unsigned integer. + /// + /// Note: the only difference to copyStream() is that a 64-bit unsigned + /// integer is used to count the number of bytes copied. +#endif + + static std::streamsize copyStreamUnbuffered(std::istream& istr, std::ostream& ostr); + /// Writes all bytes readable from istr to ostr. + /// + /// Returns the number of bytes copied. + +#if defined(POCO_HAVE_INT64) + static Poco::UInt64 copyStreamUnbuffered64(std::istream& istr, std::ostream& ostr); + /// Writes all bytes readable from istr to ostr. + /// + /// Returns the number of bytes copied as a 64-bit unsigned integer. + /// + /// Note: the only difference to copyStreamUnbuffered() is that a 64-bit unsigned + /// integer is used to count the number of bytes copied. +#endif + + static std::streamsize copyToString(std::istream& istr, std::string& str, std::size_t bufferSize = 8192); + /// Appends all bytes readable from istr to the given string, using an internal buffer. + /// + /// Returns the number of bytes copied. + +#if defined(POCO_HAVE_INT64) + static Poco::UInt64 copyToString64(std::istream& istr, std::string& str, std::size_t bufferSize = 8192); + /// Appends all bytes readable from istr to the given string, using an internal buffer. + /// + /// Returns the number of bytes copied as a 64-bit unsigned integer. + /// + /// Note: the only difference to copyToString() is that a 64-bit unsigned + /// integer is used to count the number of bytes copied. +#endif +}; + + +} // namespace Poco + + +#endif // Foundation_StreamCopier_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/StreamTokenizer.h b/contrib/libs/poco/Foundation/include/Poco/StreamTokenizer.h new file mode 100644 index 0000000000..3c5b696410 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/StreamTokenizer.h @@ -0,0 +1,97 @@ +// +// StreamTokenizer.h +// +// Library: Foundation +// Package: Streams +// Module: StreamTokenizer +// +// Definition of the StreamTokenizer class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_StreamTokenizer_INCLUDED +#define Foundation_StreamTokenizer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Token.h" +#include <istream> +#include <vector> + + +namespace Poco { + + +class Foundation_API StreamTokenizer + /// A stream tokenizer splits an input stream + /// into a sequence of tokens of different kinds. + /// Various token kinds can be registered with + /// the tokenizer. +{ +public: + StreamTokenizer(); + /// Creates a StreamTokenizer with no attached stream. + + StreamTokenizer(std::istream& istr); + /// Creates a StreamTokenizer with no attached stream. + + virtual ~StreamTokenizer(); + /// Destroys the StreamTokenizer and deletes all + /// registered tokens. + + void attachToStream(std::istream& istr); + /// Attaches the tokenizer to an input stream. + + void addToken(Token* pToken); + /// Adds a token class to the tokenizer. The + /// tokenizer takes ownership of the token and + /// deletes it when no longer needed. Comment + /// and whitespace tokens will be marked as + /// ignorable, which means that next() will not + /// return them. + + void addToken(Token* pToken, bool ignore); + /// Adds a token class to the tokenizer. The + /// tokenizer takes ownership of the token and + /// deletes it when no longer needed. + /// If ignore is true, the token will be marked + /// as ignorable, which means that next() will + /// not return it. + + const Token* next(); + /// Extracts the next token from the input stream. + /// Returns a pointer to an EOFToken if there are + /// no more characters to read. + /// Returns a pointer to an InvalidToken if an + /// invalid character is encountered. + /// If a token is marked as ignorable, it will not + /// be returned, and the next token will be + /// examined. + /// Never returns a NULL pointer. + /// You must not delete the token returned by next(). + +private: + struct TokenInfo + { + Token* pToken; + bool ignore; + }; + + typedef std::vector<TokenInfo> TokenVec; + + TokenVec _tokens; + std::istream* _pIstr; + InvalidToken _invalidToken; + EOFToken _eofToken; +}; + + +} // namespace Poco + + +#endif // Foundation_StreamTokenizer_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/StreamUtil.h b/contrib/libs/poco/Foundation/include/Poco/StreamUtil.h new file mode 100644 index 0000000000..79c94f5494 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/StreamUtil.h @@ -0,0 +1,92 @@ +// +// StreamUtil.h +// +// Library: Foundation +// Package: Streams +// Module: StreamUtil +// +// Stream implementation support. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_StreamUtil_INCLUDED +#define Foundation_StreamUtil_INCLUDED + + +#include "Poco/Foundation.h" + + +// poco_ios_init +// +// This is a workaround for a bug in the Dinkumware +// implementation of iostreams. +// +// Calling basic_ios::init() multiple times for the +// same basic_ios instance results in a memory leak +// caused by the ios' locale being allocated more than +// once, each time overwriting the old pointer. +// This usually occurs in the following scenario: +// +// class MyStreamBuf: public std::streambuf +// { +// ... +// }; +// +// class MyIOS: public virtual std::ios +// { +// public: +// MyIOS() +// { +// init(&_buf); +// } +// protected: +// MyStreamBuf _buf; +// }; +// +// class MyIStream: public MyIOS, public std::istream +// { +// ... +// }; +// +// In this scenario, std::ios::init() is called twice +// (the first time by the MyIOS constructor, the second +// time by the std::istream constructor), resulting in +// two locale objects being allocated, the pointer second +// one overwriting the pointer to the first one and thus +// causing a memory leak. +// +// The workaround is to call init() only once for each +// stream object - by the istream, ostream or iostream +// constructor, and not calling init() in ios-derived +// base classes. +// +// Some stream implementations, however, require that +// init() is called in the MyIOS constructor. +// Therefore we replace each call to init() with +// the poco_ios_init macro defined below. + + +#if !defined(POCO_IOS_INIT_HACK) + // Microsoft Visual Studio with Dinkumware STL (but not STLport) +# if defined(_MSC_VER) && (!defined(_STLP_MSVC) || defined(_STLP_NO_OWN_IOSTREAMS)) +# define POCO_IOS_INIT_HACK 1 + // QNX with Dinkumware but not GNU C++ Library +# elif defined(__QNX__) && !defined(__GLIBCPP__) +# define POCO_IOS_INIT_HACK 1 +# endif +#endif + + +#if defined(POCO_IOS_INIT_HACK) +# define poco_ios_init(buf) +#else +# define poco_ios_init(buf) init(buf) +#endif + + +#endif // Foundation_StreamUtil_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/String.h b/contrib/libs/poco/Foundation/include/Poco/String.h new file mode 100644 index 0000000000..fcf10d6de5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/String.h @@ -0,0 +1,706 @@ +// +// String.h +// +// Library: Foundation +// Package: Core +// Module: String +// +// String utility functions. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_String_INCLUDED +#define Foundation_String_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Ascii.h" +#include <cstring> +#include <algorithm> + + +namespace Poco { + + +template <class S> +S trimLeft(const S& str) + /// Returns a copy of str with all leading + /// whitespace removed. +{ + typename S::const_iterator it = str.begin(); + typename S::const_iterator end = str.end(); + + while (it != end && Ascii::isSpace(*it)) ++it; + return S(it, end); +} + + +template <class S> +S& trimLeftInPlace(S& str) + /// Removes all leading whitespace in str. +{ + typename S::iterator it = str.begin(); + typename S::iterator end = str.end(); + + while (it != end && Ascii::isSpace(*it)) ++it; + str.erase(str.begin(), it); + return str; +} + + +template <class S> +S trimRight(const S& str) + /// Returns a copy of str with all trailing + /// whitespace removed. +{ + int pos = int(str.size()) - 1; + + while (pos >= 0 && Ascii::isSpace(str[pos])) --pos; + return S(str, 0, pos + 1); +} + + +template <class S> +S& trimRightInPlace(S& str) + /// Removes all trailing whitespace in str. +{ + int pos = int(str.size()) - 1; + + while (pos >= 0 && Ascii::isSpace(str[pos])) --pos; + str.resize(pos + 1); + + return str; +} + + +template <class S> +S trim(const S& str) + /// Returns a copy of str with all leading and + /// trailing whitespace removed. +{ + int first = 0; + int last = int(str.size()) - 1; + + while (first <= last && Ascii::isSpace(str[first])) ++first; + while (last >= first && Ascii::isSpace(str[last])) --last; + + return S(str, first, last - first + 1); +} + + +template <class S> +S& trimInPlace(S& str) + /// Removes all leading and trailing whitespace in str. +{ + int first = 0; + int last = int(str.size()) - 1; + + while (first <= last && Ascii::isSpace(str[first])) ++first; + while (last >= first && Ascii::isSpace(str[last])) --last; + + str.resize(last + 1); + str.erase(0, first); + + return str; +} + + +template <class S> +S toUpper(const S& str) + /// Returns a copy of str containing all upper-case characters. +{ + typename S::const_iterator it = str.begin(); + typename S::const_iterator end = str.end(); + + S result; + result.reserve(str.size()); + while (it != end) result += static_cast<typename S::value_type>(Ascii::toUpper(*it++)); + return result; +} + + +template <class S> +S& toUpperInPlace(S& str) + /// Replaces all characters in str with their upper-case counterparts. +{ + typename S::iterator it = str.begin(); + typename S::iterator end = str.end(); + + while (it != end) { *it = static_cast<typename S::value_type>(Ascii::toUpper(*it)); ++it; } + return str; +} + + +template <class S> +S toLower(const S& str) + /// Returns a copy of str containing all lower-case characters. +{ + typename S::const_iterator it = str.begin(); + typename S::const_iterator end = str.end(); + + S result; + result.reserve(str.size()); + while (it != end) result += static_cast<typename S::value_type>(Ascii::toLower(*it++)); + return result; +} + + +template <class S> +S& toLowerInPlace(S& str) + /// Replaces all characters in str with their lower-case counterparts. +{ + typename S::iterator it = str.begin(); + typename S::iterator end = str.end(); + + while (it != end) { *it = static_cast<typename S::value_type>(Ascii::toLower(*it)); ++it; } + return str; +} + + +#if !defined(POCO_NO_TEMPLATE_ICOMPARE) + + +template <class S, class It> +int icompare( + const S& str, + typename S::size_type pos, + typename S::size_type n, + It it2, + It end2) + /// Case-insensitive string comparison +{ + typename S::size_type sz = str.size(); + if (pos > sz) pos = sz; + if (pos + n > sz) n = sz - pos; + It it1 = str.begin() + pos; + It end1 = str.begin() + pos + n; + while (it1 != end1 && it2 != end2) + { + typename S::value_type c1(static_cast<typename S::value_type>(Ascii::toLower(*it1))); + typename S::value_type c2(static_cast<typename S::value_type>(Ascii::toLower(*it2))); + if (c1 < c2) + return -1; + else if (c1 > c2) + return 1; + ++it1; ++it2; + } + + if (it1 == end1) + return it2 == end2 ? 0 : -1; + else + return 1; +} + + +template <class S> +int icompare(const S& str1, const S& str2) + // A special optimization for an often used case. +{ + typename S::const_iterator it1(str1.begin()); + typename S::const_iterator end1(str1.end()); + typename S::const_iterator it2(str2.begin()); + typename S::const_iterator end2(str2.end()); + while (it1 != end1 && it2 != end2) + { + typename S::value_type c1(static_cast<typename S::value_type>(Ascii::toLower(*it1))); + typename S::value_type c2(static_cast<typename S::value_type>(Ascii::toLower(*it2))); + if (c1 < c2) + return -1; + else if (c1 > c2) + return 1; + ++it1; ++it2; + } + + if (it1 == end1) + return it2 == end2 ? 0 : -1; + else + return 1; +} + + +template <class S> +int icompare(const S& str1, typename S::size_type n1, const S& str2, typename S::size_type n2) +{ + if (n2 > str2.size()) n2 = str2.size(); + return icompare(str1, 0, n1, str2.begin(), str2.begin() + n2); +} + + +template <class S> +int icompare(const S& str1, typename S::size_type n, const S& str2) +{ + if (n > str2.size()) n = str2.size(); + return icompare(str1, 0, n, str2.begin(), str2.begin() + n); +} + + +template <class S> +int icompare(const S& str1, typename S::size_type pos, typename S::size_type n, const S& str2) +{ + return icompare(str1, pos, n, str2.begin(), str2.end()); +} + + +template <class S> +int icompare( + const S& str1, + typename S::size_type pos1, + typename S::size_type n1, + const S& str2, + typename S::size_type pos2, + typename S::size_type n2) +{ + typename S::size_type sz2 = str2.size(); + if (pos2 > sz2) pos2 = sz2; + if (pos2 + n2 > sz2) n2 = sz2 - pos2; + return icompare(str1, pos1, n1, str2.begin() + pos2, str2.begin() + pos2 + n2); +} + + +template <class S> +int icompare( + const S& str1, + typename S::size_type pos1, + typename S::size_type n, + const S& str2, + typename S::size_type pos2) +{ + typename S::size_type sz2 = str2.size(); + if (pos2 > sz2) pos2 = sz2; + if (pos2 + n > sz2) n = sz2 - pos2; + return icompare(str1, pos1, n, str2.begin() + pos2, str2.begin() + pos2 + n); +} + + +template <class S> +int icompare( + const S& str, + typename S::size_type pos, + typename S::size_type n, + const typename S::value_type* ptr) +{ + poco_check_ptr (ptr); + typename S::size_type sz = str.size(); + if (pos > sz) pos = sz; + if (pos + n > sz) n = sz - pos; + typename S::const_iterator it = str.begin() + pos; + typename S::const_iterator end = str.begin() + pos + n; + while (it != end && *ptr) + { + typename S::value_type c1(static_cast<typename S::value_type>(Ascii::toLower(*it))); + typename S::value_type c2(static_cast<typename S::value_type>(Ascii::toLower(*ptr))); + if (c1 < c2) + return -1; + else if (c1 > c2) + return 1; + ++it; ++ptr; + } + + if (it == end) + return *ptr == 0 ? 0 : -1; + else + return 1; +} + + +template <class S> +int icompare( + const S& str, + typename S::size_type pos, + const typename S::value_type* ptr) +{ + return icompare(str, pos, str.size() - pos, ptr); +} + + +template <class S> +int icompare( + const S& str, + const typename S::value_type* ptr) +{ + return icompare(str, 0, str.size(), ptr); +} + + +#else + + +int Foundation_API icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, std::string::const_iterator it2, std::string::const_iterator end2); +int Foundation_API icompare(const std::string& str1, const std::string& str2); +int Foundation_API icompare(const std::string& str1, std::string::size_type n1, const std::string& str2, std::string::size_type n2); +int Foundation_API icompare(const std::string& str1, std::string::size_type n, const std::string& str2); +int Foundation_API icompare(const std::string& str1, std::string::size_type pos, std::string::size_type n, const std::string& str2); +int Foundation_API icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n1, const std::string& str2, std::string::size_type pos2, std::string::size_type n2); +int Foundation_API icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n, const std::string& str2, std::string::size_type pos2); +int Foundation_API icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, const std::string::value_type* ptr); +int Foundation_API icompare(const std::string& str, std::string::size_type pos, const std::string::value_type* ptr); +int Foundation_API icompare(const std::string& str, const std::string::value_type* ptr); + + +#endif + + +template <class S> +S translate(const S& str, const S& from, const S& to) + /// Returns a copy of str with all characters in + /// from replaced by the corresponding (by position) + /// characters in to. If there is no corresponding + /// character in to, the character is removed from + /// the copy. +{ + S result; + result.reserve(str.size()); + typename S::const_iterator it = str.begin(); + typename S::const_iterator end = str.end(); + typename S::size_type toSize = to.size(); + while (it != end) + { + typename S::size_type pos = from.find(*it); + if (pos == S::npos) + { + result += *it; + } + else + { + if (pos < toSize) result += to[pos]; + } + ++it; + } + return result; +} + + +template <class S> +S translate(const S& str, const typename S::value_type* from, const typename S::value_type* to) +{ + poco_check_ptr (from); + poco_check_ptr (to); + return translate(str, S(from), S(to)); +} + + +template <class S> +S& translateInPlace(S& str, const S& from, const S& to) + /// Replaces in str all occurrences of characters in from + /// with the corresponding (by position) characters in to. + /// If there is no corresponding character, the character + /// is removed. +{ + str = translate(str, from, to); + return str; +} + + +template <class S> +S translateInPlace(S& str, const typename S::value_type* from, const typename S::value_type* to) +{ + poco_check_ptr (from); + poco_check_ptr (to); + str = translate(str, S(from), S(to)); +#if defined(__SUNPRO_CC) +// Fix around the RVO bug in SunStudio 12.4 + S ret(str); + return ret; +#else + return str; +#endif +} + + +#if !defined(POCO_NO_TEMPLATE_ICOMPARE) + + +template <class S> +S& replaceInPlace(S& str, const S& from, const S& to, typename S::size_type start = 0) +{ + poco_assert (from.size() > 0); + + S result; + typename S::size_type pos = 0; + result.append(str, 0, start); + do + { + pos = str.find(from, start); + if (pos != S::npos) + { + result.append(str, start, pos - start); + result.append(to); + start = pos + from.length(); + } + else result.append(str, start, str.size() - start); + } + while (pos != S::npos); + str.swap(result); + return str; +} + + +template <class S> +S& replaceInPlace(S& str, const typename S::value_type* from, const typename S::value_type* to, typename S::size_type start = 0) +{ + poco_assert (*from); + + S result; + typename S::size_type pos = 0; + typename S::size_type fromLen = std::strlen(from); + result.append(str, 0, start); + do + { + pos = str.find(from, start); + if (pos != S::npos) + { + result.append(str, start, pos - start); + result.append(to); + start = pos + fromLen; + } + else result.append(str, start, str.size() - start); + } + while (pos != S::npos); + str.swap(result); + return str; +} + + +template <class S> +S& replaceInPlace(S& str, const typename S::value_type from, const typename S::value_type to = 0, typename S::size_type start = 0) +{ + if (from == to) return str; + + typename S::size_type pos = 0; + do + { + pos = str.find(from, start); + if (pos != S::npos) + { + if (to) str[pos] = to; + else str.erase(pos, 1); + } + } while (pos != S::npos); + + return str; +} + + +template <class S> +S& removeInPlace(S& str, const typename S::value_type ch, typename S::size_type start = 0) +{ + return replaceInPlace(str, ch, 0, start); +} + + +template <class S> +S replace(const S& str, const S& from, const S& to, typename S::size_type start = 0) + /// Replace all occurrences of from (which must not be the empty string) + /// in str with to, starting at position start. +{ + S result(str); + replaceInPlace(result, from, to, start); + return result; +} + + +template <class S> +S replace(const S& str, const typename S::value_type* from, const typename S::value_type* to, typename S::size_type start = 0) +{ + S result(str); + replaceInPlace(result, from, to, start); + return result; +} + + +template <class S> +S replace(const S& str, const typename S::value_type from, const typename S::value_type to = 0, typename S::size_type start = 0) +{ + S result(str); + replaceInPlace(result, from, to, start); + return result; +} + + +template <class S> +S remove(const S& str, const typename S::value_type ch, typename S::size_type start = 0) +{ + S result(str); + replaceInPlace(result, ch, 0, start); + return result; +} + + +#else + + +Foundation_API std::string replace(const std::string& str, const std::string& from, const std::string& to, std::string::size_type start = 0); +Foundation_API std::string replace(const std::string& str, const std::string::value_type* from, const std::string::value_type* to, std::string::size_type start = 0); +Foundation_API std::string replace(const std::string& str, const std::string::value_type from, const std::string::value_type to = 0, std::string::size_type start = 0); +Foundation_API std::string remove(const std::string& str, const std::string::value_type ch, std::string::size_type start = 0); +Foundation_API std::string& replaceInPlace(std::string& str, const std::string& from, const std::string& to, std::string::size_type start = 0); +Foundation_API std::string& replaceInPlace(std::string& str, const std::string::value_type* from, const std::string::value_type* to, std::string::size_type start = 0); +Foundation_API std::string& replaceInPlace(std::string& str, const std::string::value_type from, const std::string::value_type to = 0, std::string::size_type start = 0); +Foundation_API std::string& removeInPlace(std::string& str, const std::string::value_type ch, std::string::size_type start = 0); + + +#endif + + +template <class S> +S cat(const S& s1, const S& s2) + /// Concatenates two strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size()); + result.append(s2); + return result; +} + + +template <class S> +S cat(const S& s1, const S& s2, const S& s3) + /// Concatenates three strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size() + s3.size()); + result.append(s2); + result.append(s3); + return result; +} + + +template <class S> +S cat(const S& s1, const S& s2, const S& s3, const S& s4) + /// Concatenates four strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size() + s3.size() + s4.size()); + result.append(s2); + result.append(s3); + result.append(s4); + return result; +} + + +template <class S> +S cat(const S& s1, const S& s2, const S& s3, const S& s4, const S& s5) + /// Concatenates five strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size()); + result.append(s2); + result.append(s3); + result.append(s4); + result.append(s5); + return result; +} + + +template <class S> +S cat(const S& s1, const S& s2, const S& s3, const S& s4, const S& s5, const S& s6) + /// Concatenates six strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size() + s6.size()); + result.append(s2); + result.append(s3); + result.append(s4); + result.append(s5); + result.append(s6); + return result; +} + + +template <class S, class It> +S cat(const S& delim, const It& begin, const It& end) + /// Concatenates a sequence of strings, delimited + /// by the string given in delim. +{ + S result; + for (It it = begin; it != end; ++it) + { + if (!result.empty()) result.append(delim); + result += *it; + } + return result; +} + + +// +// case-insensitive string equality +// + + +template <typename charT> +struct i_char_traits : public std::char_traits<charT> +{ + inline static bool eq(charT c1, charT c2) + { + return Ascii::toLower(c1) == Ascii::toLower(c2); + } + + inline static bool ne(charT c1, charT c2) + { + return !eq(c1, c2); + } + + inline static bool lt(charT c1, charT c2) + { + return Ascii::toLower(c1) < Ascii::toLower(c2); + } + + static int compare(const charT* s1, const charT* s2, std::size_t n) + { + for (int i = 0; i < n && s1 && s2; ++i, ++s1, ++s2) + { + if (Ascii::toLower(*s1) == Ascii::toLower(*s2)) continue; + else if (Ascii::toLower(*s1) < Ascii::toLower(*s2)) return -1; + else return 1; + } + + return 0; + } + + static const charT* find(const charT* s, int n, charT a) + { + while(n-- > 0 && Ascii::toLower(*s) != Ascii::toLower(a)) { ++s; } + return s; + } +}; + + +typedef std::basic_string<char, i_char_traits<char> > istring; + /// Case-insensitive std::string counterpart. + + +template<typename T> +std::size_t isubstr(const T& str, const T& sought) + /// Case-insensitive substring; searches for a substring + /// without regards to case. +{ + typename T::const_iterator it = std::search(str.begin(), str.end(), + sought.begin(), sought.end(), + i_char_traits<typename T::value_type>::eq); + + if (it != str.end()) return it - str.begin(); + else return static_cast<std::size_t>(T::npos); +} + + +struct CILess + /// Case-insensitive less-than functor; useful for standard maps + /// and sets with std::strings keys and case-insensitive ordering + /// requirement. +{ + inline bool operator() (const std::string& s1, const std::string& s2) const + { + return icompare(s1, s2) < 0; + } +}; + + +} // namespace Poco + + +#endif // Foundation_String_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/StringTokenizer.h b/contrib/libs/poco/Foundation/include/Poco/StringTokenizer.h new file mode 100644 index 0000000000..e4bfd469f2 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/StringTokenizer.h @@ -0,0 +1,135 @@ +// +// StringTokenizer.h +// +// Library: Foundation +// Package: Core +// Module: StringTokenizer +// +// Definition of the StringTokenizer class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_StringTokenizer_INCLUDED +#define Foundation_StringTokenizer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include <vector> +#include <cstddef> + + +namespace Poco { + + +class Foundation_API StringTokenizer + /// A simple tokenizer that splits a string into + /// tokens, which are separated by separator characters. + /// An iterator is used to iterate over all tokens. +{ +public: + enum Options + { + TOK_IGNORE_EMPTY = 1, /// ignore empty tokens + TOK_TRIM = 2 /// remove leading and trailing whitespace from tokens + }; + + typedef std::vector<std::string> TokenVec; + typedef TokenVec::const_iterator Iterator; + + StringTokenizer(const std::string& str, const std::string& separators, int options = 0); + /// Splits the given string into tokens. The tokens are expected to be + /// separated by one of the separator characters given in separators. + /// Additionally, options can be specified: + /// * TOK_IGNORE_EMPTY: empty tokens are ignored + /// * TOK_TRIM: trailing and leading whitespace is removed from tokens. + + ~StringTokenizer(); + /// Destroys the tokenizer. + + Iterator begin() const; + Iterator end() const; + + const std::string& operator [] (std::size_t index) const; + /// Returns const reference the index'th token. + /// Throws a RangeException if the index is out of range. + + std::string& operator [] (std::size_t index); + /// Returns reference to the index'th token. + /// Throws a RangeException if the index is out of range. + + bool has(const std::string& token) const; + /// Returns true if token exists, false otherwise. + + std::string::size_type find(const std::string& token, std::string::size_type pos = 0) const; + /// Returns the index of the first occurence of the token + /// starting at position pos. + /// Throws a NotFoundException if the token is not found. + + std::size_t replace(const std::string& oldToken, const std::string& newToken, std::string::size_type pos = 0); + /// Starting at position pos, replaces all subsequent tokens having value + /// equal to oldToken with newToken. + /// Returns the number of modified tokens. + + std::size_t count() const; + /// Returns the total number of tokens. + + std::size_t count(const std::string& token) const; + /// Returns the number of tokens equal to the specified token. + +private: + StringTokenizer(const StringTokenizer&); + StringTokenizer& operator = (const StringTokenizer&); + + void trim(std::string& token); + + TokenVec _tokens; +}; + + +// +// inlines +// + + +inline StringTokenizer::Iterator StringTokenizer::begin() const +{ + return _tokens.begin(); +} + + +inline StringTokenizer::Iterator StringTokenizer::end() const +{ + return _tokens.end(); +} + + +inline std::string& StringTokenizer::operator [] (std::size_t index) +{ + if (index >= _tokens.size()) throw RangeException(); + return _tokens[index]; +} + + +inline const std::string& StringTokenizer::operator [] (std::size_t index) const +{ + if (index >= _tokens.size()) throw RangeException(); + return _tokens[index]; +} + + +inline std::size_t StringTokenizer::count() const +{ + return _tokens.size(); +} + + +} // namespace Poco + + +#endif // Foundation_StringTokenizer_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SynchronizedObject.h b/contrib/libs/poco/Foundation/include/Poco/SynchronizedObject.h new file mode 100644 index 0000000000..b697f48e66 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SynchronizedObject.h @@ -0,0 +1,131 @@ +// +// SynchronizedObject.h +// +// Library: Foundation +// Package: Threading +// Module: SynchronizedObject +// +// Definition of the SynchronizedObject class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SynchronizedObject_INCLUDED +#define Foundation_SynchronizedObject_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" + + +namespace Poco { + + +class Foundation_API SynchronizedObject + /// This class aggregates a Mutex and an Event + /// and can act as a base class for all objects + /// requiring synchronization in a multithreaded + /// scenario. +{ +public: + typedef Poco::ScopedLock<SynchronizedObject> ScopedLock; + + SynchronizedObject(); + /// Creates the object. + + virtual ~SynchronizedObject(); + /// Destroys the object. + + void lock() const; + /// Locks the object. Blocks if the object + /// is locked by another thread. + + bool tryLock() const; + /// Tries to lock the object. Returns false immediately + /// if the object is already locked by another thread + /// Returns true if the object was successfully locked. + + void unlock() const; + /// Unlocks the object so that it can be locked by + /// other threads. + + void notify() const; + /// Signals the object. + /// Exactly only one thread waiting for the object + /// can resume execution. + + void wait() const; + /// Waits for the object to become signalled. + + void wait(long milliseconds) const; + /// Waits for the object to become signalled. + /// Throws a TimeoutException if the object + /// does not become signalled within the specified + /// time interval. + + bool tryWait(long milliseconds) const; + /// Waits for the object to become signalled. + /// Returns true if the object + /// became signalled within the specified + /// time interval, false otherwise. + +private: + mutable Mutex _mutex; + mutable Event _event; +}; + + +// +// inlines +// +inline void SynchronizedObject::lock() const +{ + _mutex.lock(); +} + + +inline bool SynchronizedObject::tryLock() const +{ + return _mutex.tryLock(); +} + + +inline void SynchronizedObject::unlock() const +{ + _mutex.unlock(); +} + + +inline void SynchronizedObject::notify() const +{ + _event.set(); +} + + +inline void SynchronizedObject::wait() const +{ + _event.wait(); +} + + +inline void SynchronizedObject::wait(long milliseconds) const +{ + _event.wait(milliseconds); +} + + +inline bool SynchronizedObject::tryWait(long milliseconds) const +{ + return _event.tryWait(milliseconds); +} + + +} // namespace Poco + + +#endif // Foundation_SynchronizedObject_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/SyslogChannel.h b/contrib/libs/poco/Foundation/include/Poco/SyslogChannel.h new file mode 100644 index 0000000000..4c304e8c0d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/SyslogChannel.h @@ -0,0 +1,109 @@ +// +// SyslogChannel.h +// +// Library: Foundation +// Package: Logging +// Module: SyslogChannel +// +// Definition of the SyslogChannel class specific to UNIX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_SyslogChannel_INCLUDED +#define Foundation_SyslogChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" + + +namespace Poco { + + +class Foundation_API SyslogChannel: public Channel + /// This Unix-only channel works with the Unix syslog service. +{ +public: + enum Option + { + SYSLOG_PID = 0x01, /// log the pid with each message + SYSLOG_CONS = 0x02, /// log on the console if errors in sending + SYSLOG_NDELAY = 0x08, /// don't delay open + SYSLOG_PERROR = 0x20 /// log to stderr as well (not supported on all platforms) + }; + + enum Facility + { + SYSLOG_KERN = ( 0<<3), /// kernel messages + SYSLOG_USER = ( 1<<3), /// random user-level messages + SYSLOG_MAIL = ( 2<<3), /// mail system + SYSLOG_DAEMON = ( 3<<3), /// system daemons + SYSLOG_AUTH = ( 4<<3), /// security/authorization messages + SYSLOG_SYSLOG = ( 5<<3), /// messages generated internally by syslogd + SYSLOG_LPR = ( 6<<3), /// line printer subsystem + SYSLOG_NEWS = ( 7<<3), /// network news subsystem + SYSLOG_UUCP = ( 8<<3), /// UUCP subsystem + SYSLOG_CRON = ( 9<<3), /// clock daemon + SYSLOG_AUTHPRIV = (10<<3), /// security/authorization messages (private) + SYSLOG_FTP = (11<<3), /// ftp daemon + SYSLOG_LOCAL0 = (16<<3), /// reserved for local use + SYSLOG_LOCAL1 = (17<<3), /// reserved for local use + SYSLOG_LOCAL2 = (18<<3), /// reserved for local use + SYSLOG_LOCAL3 = (19<<3), /// reserved for local use + SYSLOG_LOCAL4 = (20<<3), /// reserved for local use + SYSLOG_LOCAL5 = (21<<3), /// reserved for local use + SYSLOG_LOCAL6 = (22<<3), /// reserved for local use + SYSLOG_LOCAL7 = (23<<3) /// reserved for local use + }; + + SyslogChannel(); + /// Creates a SyslogChannel. + + SyslogChannel(const std::string& name, int options = SYSLOG_CONS, int facility = SYSLOG_USER); + /// Creates a SyslogChannel with the given name, options and facility. + + void open(); + /// Opens the SyslogChannel. + + void close(); + /// Closes the SyslogChannel. + + void log(const Message& msg); + /// Sens the message's text to the syslog service. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given value. + /// + /// The following properties are supported: + /// * name: The name used to identify the source of log messages. + /// * facility: The facility added to each log message. See the Facility enumeration for a list of supported values. + /// * options: The logging options. See the Option enumeration for a list of supported values. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + + static const std::string PROP_NAME; + static const std::string PROP_FACILITY; + static const std::string PROP_OPTIONS; + +protected: + ~SyslogChannel(); + static int getPrio(const Message& msg); + +private: + std::string _name; + int _options; + int _facility; + bool _open; +}; + + +} // namespace Poco + + +#endif // Foundation_SyslogChannel_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Task.h b/contrib/libs/poco/Foundation/include/Poco/Task.h new file mode 100644 index 0000000000..1df83120ba --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Task.h @@ -0,0 +1,191 @@ +// +// Task.h +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Definition of the Task class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Task_INCLUDED +#define Foundation_Task_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/RefCountedObject.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" + +#include <atomic> + + +namespace Poco { + + +class TaskManager; +class Notification; +class NotificationCenter; + + +class Foundation_API Task: public Runnable, public RefCountedObject + /// A Task is a subclass of Runnable that has a name + /// and supports progress reporting and cancellation. + /// + /// A TaskManager object can be used to take care of the + /// lifecycle of a Task. +{ +public: + enum TaskState + { + TASK_IDLE, + TASK_STARTING, + TASK_RUNNING, + TASK_CANCELLING, + TASK_FINISHED + }; + + Task(const std::string& name); + /// Creates the Task. + + const std::string& name() const; + /// Returns the task's name. + + float progress() const; + /// Returns the task's progress. + /// The value will be between 0.0 (just started) + /// and 1.0 (completed). + + virtual void cancel(); + /// Requests the task to cancel itself. For cancellation + /// to work, the task's runTask() method must periodically + /// call isCancelled() and react accordingly. + /// + /// Can be overridden to implement custom behavior, + /// but the base class implementation of cancel() should + /// be called to ensure proper behavior. + + bool isCancelled() const; + /// Returns true if cancellation of the task has been + /// requested. + /// + /// A Task's runTask() method should periodically + /// call this method and stop whatever it is doing in an + /// orderly way when this method returns true. + + TaskState state() const; + /// Returns the task's current state. + + void reset(); + /// Sets the task's progress to zero and clears the + /// cancel flag. + + virtual void runTask() = 0; + /// Do whatever the task needs to do. Must + /// be overridden by subclasses. + + void run(); + /// Calls the task's runTask() method and notifies the owner + /// of the task's start and completion. + +protected: + bool sleep(long milliseconds); + /// Suspends the current thread for the specified + /// amount of time. + /// + /// If the task is cancelled while it is sleeping, + /// sleep() will return immediately and the return + /// value will be true. If the time interval + /// passes without the task being cancelled, the + /// return value is false. + /// + /// A Task should use this method in favor of Thread::sleep(). + + void setProgress(float progress); + /// Sets the task's progress. + /// The value should be between 0.0 (just started) + /// and 1.0 (completed). + + virtual void postNotification(Notification* pNf); + /// Posts a notification to the task manager's + /// notification center. + /// + /// A task can use this method to post custom + /// notifications about its progress. + + void setOwner(TaskManager* pOwner); + /// Sets the (optional) owner of the task. + + TaskManager* getOwner() const; + /// Returns the owner of the task, which may be NULL. + + void setState(TaskState state); + /// Sets the task's state. + + virtual ~Task(); + /// Destroys the Task. + +private: + Task(); + Task(const Task&); + Task& operator = (const Task&); + + std::string _name; + TaskManager* _pOwner; + float _progress; + std::atomic<TaskState> _state; + Event _cancelEvent; + mutable FastMutex _mutex; + + friend class TaskManager; +}; + + +// +// inlines +// +inline const std::string& Task::name() const +{ + return _name; +} + + +inline float Task::progress() const +{ + FastMutex::ScopedLock lock(_mutex); + + return _progress; +} + + +inline bool Task::isCancelled() const +{ + return _state == TASK_CANCELLING; +} + + +inline Task::TaskState Task::state() const +{ + return _state; +} + + +inline TaskManager* Task::getOwner() const +{ + FastMutex::ScopedLock lock(_mutex); + + return _pOwner; +} + + +} // namespace Poco + + +#endif // Foundation_Task_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TaskManager.h b/contrib/libs/poco/Foundation/include/Poco/TaskManager.h new file mode 100644 index 0000000000..3d6e7f1cc1 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TaskManager.h @@ -0,0 +1,137 @@ +// +// TaskManager.h +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Definition of the TaskManager class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TaskManager_INCLUDED +#define Foundation_TaskManager_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/Task.h" +#include "Poco/AutoPtr.h" +#include "Poco/NotificationCenter.h" +#include "Poco/Timestamp.h" +#include <list> + + +namespace Poco { + + +class Notification; +class ThreadPool; +class Exception; + + +class Foundation_API TaskManager + /// The TaskManager manages a collection of tasks + /// and monitors their lifetime. + /// + /// A TaskManager has a built-in NotificationCenter that + /// is used to send out notifications on task progress + /// and task states. See the TaskNotification class and its + /// subclasses for the various events that result in a notification. + /// To keep the number of notifications small, a TaskProgressNotification + /// will only be sent out once in 100 milliseconds. +{ +public: + typedef AutoPtr<Task> TaskPtr; + typedef std::list<TaskPtr> TaskList; + + TaskManager(); + /// Creates the TaskManager, using the + /// default ThreadPool. + + TaskManager(ThreadPool& pool); + /// Creates the TaskManager, using the + /// given ThreadPool. + + ~TaskManager(); + /// Destroys the TaskManager. + + void start(Task* pTask); + /// Starts the given task in a thread obtained + /// from the thread pool. + /// + /// The TaskManager takes ownership of the Task object + /// and deletes it when it it finished. + + void cancelAll(); + /// Requests cancellation of all tasks. + + void joinAll(); + /// Waits for the completion of all the threads + /// in the TaskManager's thread pool. + /// + /// Note: joinAll() will wait for ALL tasks in the + /// TaskManager's ThreadPool to complete. If the + /// ThreadPool has threads created by other + /// facilities, these threads must also complete + /// before joinAll() can return. + + TaskList taskList() const; + /// Returns a copy of the internal task list. + + int count() const; + /// Returns the number of tasks in the internal task list. + + void addObserver(const AbstractObserver& observer); + /// Registers an observer with the NotificationCenter. + /// Usage: + /// Observer<MyClass, MyNotification> obs(*this, &MyClass::handleNotification); + /// notificationCenter.addObserver(obs); + + void removeObserver(const AbstractObserver& observer); + /// Unregisters an observer with the NotificationCenter. + + static const int MIN_PROGRESS_NOTIFICATION_INTERVAL; + +protected: + void postNotification(const Notification::Ptr& pNf); + /// Posts a notification to the task manager's + /// notification center. + + void taskStarted(Task* pTask); + void taskProgress(Task* pTask, float progress); + void taskCancelled(Task* pTask); + void taskFinished(Task* pTask); + void taskFailed(Task* pTask, const Exception& exc); + +private: + ThreadPool& _threadPool; + TaskList _taskList; + Timestamp _lastProgressNotification; + NotificationCenter _nc; + mutable FastMutex _mutex; + + friend class Task; +}; + + +// +// inlines +// +inline int TaskManager::count() const +{ + FastMutex::ScopedLock lock(_mutex); + + return (int) _taskList.size(); +} + + +} // namespace Poco + + +#endif // Foundation_TaskManager_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TaskNotification.h b/contrib/libs/poco/Foundation/include/Poco/TaskNotification.h new file mode 100644 index 0000000000..da2ac6240b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TaskNotification.h @@ -0,0 +1,170 @@ +// +// TaskNotification.h +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Definition of the TaskNotification class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TaskNotification_INCLUDED +#define Foundation_TaskNotification_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Notification.h" +#include "Poco/Task.h" + + +namespace Poco { + + +class Foundation_API TaskNotification: public Notification + /// Base class for TaskManager notifications. +{ +public: + TaskNotification(Task* pTask); + /// Creates the TaskNotification. + + Task* task() const; + /// Returns the subject of the notification. + +protected: + virtual ~TaskNotification(); + /// Destroys the TaskNotification. + +private: + Task* _pTask; +}; + + +class Foundation_API TaskStartedNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has been started. +{ +public: + TaskStartedNotification(Task* pTask); + +protected: + ~TaskStartedNotification(); +}; + + +class Foundation_API TaskCancelledNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has been cancelled. +{ +public: + TaskCancelledNotification(Task* pTask); + +protected: + ~TaskCancelledNotification(); +}; + + +class Foundation_API TaskFinishedNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has finished. +{ +public: + TaskFinishedNotification(Task* pTask); + +protected: + ~TaskFinishedNotification(); +}; + + +class Foundation_API TaskFailedNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has failed with an exception. +{ +public: + TaskFailedNotification(Task* pTask, const Exception& exc); + + const Exception& reason() const; + +protected: + ~TaskFailedNotification(); + +private: + Exception* _pException; +}; + + +class Foundation_API TaskProgressNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// a task when its progress changes. +{ +public: + TaskProgressNotification(Task* pTask, float progress); + + float progress() const; + +protected: + ~TaskProgressNotification(); + +private: + float _progress; +}; + + +template <class C> +class TaskCustomNotification: public TaskNotification + /// This is a template for "custom" notification. + /// Unlike other notifications, this notification + /// is instantiated and posted by the task itself. + /// The purpose is to provide generic notifiation + /// mechanism between the task and its observer(s). +{ +public: + TaskCustomNotification(Task* pTask, const C& rCustom): + TaskNotification(pTask), + _custom(rCustom) + { + } + + const C& custom() const + { + return _custom; + } + +protected: + ~TaskCustomNotification(){}; + +private: + C _custom; +}; + + +// +// inlines +// +inline Task* TaskNotification::task() const +{ + return _pTask; +} + + +inline const Exception& TaskFailedNotification::reason() const +{ + return *_pException; +} + + +inline float TaskProgressNotification::progress() const +{ + return _progress; +} + + +} // namespace Poco + + +#endif // Foundation_TaskNotification_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TeeStream.h b/contrib/libs/poco/Foundation/include/Poco/TeeStream.h new file mode 100644 index 0000000000..07744d8341 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TeeStream.h @@ -0,0 +1,132 @@ +// +// TeeStream.h +// +// Library: Foundation +// Package: Streams +// Module: TeeStream +// +// Definition of the TeeStream class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TeeStream_INCLUDED +#define Foundation_TeeStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include <vector> +#include <istream> +#include <ostream> + + +namespace Poco { + + +class Foundation_API TeeStreamBuf: public UnbufferedStreamBuf + /// This stream buffer copies all data written to or + /// read from it to one or multiple output streams. +{ +public: + TeeStreamBuf(); + /// Creates an unconnected CountingStreamBuf. + /// Use addStream() to attach output streams. + + TeeStreamBuf(std::istream& istr); + /// Creates the CountingStreamBuf and connects it + /// to the given input stream. + + TeeStreamBuf(std::ostream& ostr); + /// Creates the CountingStreamBuf and connects it + /// to the given output stream. + + ~TeeStreamBuf(); + /// Destroys the CountingStream. + + void addStream(std::ostream& ostr); + /// Adds the given output stream. + +protected: + int readFromDevice(); + int writeToDevice(char c); + +private: + typedef std::vector<std::ostream*> StreamVec; + + std::istream* _pIstr; + StreamVec _streams; +}; + + +class Foundation_API TeeIOS: public virtual std::ios + /// The base class for TeeInputStream and TeeOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + TeeIOS(); + /// Creates the basic stream and leaves it unconnected. + + TeeIOS(std::istream& istr); + /// Creates the basic stream and connects it + /// to the given input stream. + + TeeIOS(std::ostream& ostr); + /// Creates the basic stream and connects it + /// to the given output stream. + + ~TeeIOS(); + /// Destroys the stream. + + void addStream(std::ostream& ostr); + /// Adds the given output stream. + + TeeStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + TeeStreamBuf _buf; +}; + + +class Foundation_API TeeInputStream: public TeeIOS, public std::istream + /// This stream copies all characters read through it + /// to one or multiple output streams. +{ +public: + TeeInputStream(std::istream& istr); + /// Creates the TeeInputStream and connects it + /// to the given input stream. + + ~TeeInputStream(); + /// Destroys the TeeInputStream. +}; + + +class Foundation_API TeeOutputStream: public TeeIOS, public std::ostream + /// This stream copies all characters written to it + /// to one or multiple output streams. +{ +public: + TeeOutputStream(); + /// Creates an unconnected TeeOutputStream. + + TeeOutputStream(std::ostream& ostr); + /// Creates the TeeOutputStream and connects it + /// to the given input stream. + + ~TeeOutputStream(); + /// Destroys the TeeOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_TeeStream_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TemporaryFile.h b/contrib/libs/poco/Foundation/include/Poco/TemporaryFile.h new file mode 100644 index 0000000000..9246846c29 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TemporaryFile.h @@ -0,0 +1,84 @@ +// +// TemporaryFile.h +// +// Library: Foundation +// Package: Filesystem +// Module: TemporaryFile +// +// Definition of the TemporaryFile class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TemporaryFile_INCLUDED +#define Foundation_TemporaryFile_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/File.h" + + +namespace Poco { + + +class Foundation_API TemporaryFile: public File + /// The TemporaryFile class helps with the handling + /// of temporary files. + /// A unique name for the temporary file is + /// automatically chosen and the file is placed + /// in the directory reserved for temporary + /// files (see Path::temp()). + /// Obtain the path by calling the path() method + /// (inherited from File). + /// + /// The TemporaryFile class does not actually + /// create the file - this is up to the application. + /// The class does, however, delete the temporary + /// file - either in the destructor, or immediately + /// before the application terminates. +{ +public: + TemporaryFile(); + /// Creates the TemporaryFile. + + TemporaryFile(const std::string& tempDir); + /// Creates the TemporaryFile using the given directory. + + ~TemporaryFile(); + /// Destroys the TemporaryFile and + /// deletes the corresponding file on + /// disk unless keep() or keepUntilExit() + /// has been called. + + void keep(); + /// Disables automatic deletion of the file in + /// the destructor. + + void keepUntilExit(); + /// Disables automatic deletion of the file in + /// the destructor, but registers the file + /// for deletion at process termination. + + static void registerForDeletion(const std::string& path); + /// Registers the given file for deletion + /// at process termination. + + static std::string tempName(const std::string& tempDir = ""); + /// Returns a unique path name for a temporary + /// file in the system's scratch directory (see Path::temp()) + /// if tempDir is empty or in the directory specified in tempDir + /// otherwise. + +private: + bool _keep; +}; + + +} // namespace Poco + + +#endif // Foundation_TemporaryFile_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TextBufferIterator.h b/contrib/libs/poco/Foundation/include/Poco/TextBufferIterator.h new file mode 100644 index 0000000000..d8eda84175 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TextBufferIterator.h @@ -0,0 +1,145 @@ +// +// TextBufferIterator.h +// +// Library: Foundation +// Package: Text +// Module: TextBufferIterator +// +// Definition of the TextBufferIterator class. +// +// Copyright (c) 2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TextBufferIterator_INCLUDED +#define Foundation_TextBufferIterator_INCLUDED + + +#include "Poco/Foundation.h" +#include <cstdlib> + + +namespace Poco { + + +class TextEncoding; + + +class Foundation_API TextBufferIterator + /// An unidirectional iterator for iterating over characters in a buffer. + /// The TextBufferIterator uses a TextEncoding object to + /// work with multi-byte character encodings like UTF-8. + /// Characters are reported in Unicode. + /// + /// Example: Count the number of UTF-8 characters in a buffer. + /// + /// UTF8Encoding utf8Encoding; + /// char buffer[] = "..."; + /// TextBufferIterator it(buffer, utf8Encoding); + /// TextBufferIterator end(it.end()); + /// int n = 0; + /// while (it != end) { ++n; ++it; } + /// + /// NOTE: When an UTF-16 encoding is used, surrogate pairs will be + /// reported as two separate characters, due to restrictions of + /// the TextEncoding class. + /// + /// For iterating over the characters in a std::string, see the + /// TextIterator class. +{ +public: + TextBufferIterator(); + /// Creates an uninitialized TextBufferIterator. + + TextBufferIterator(const char* begin, const TextEncoding& encoding); + /// Creates a TextBufferIterator for the given buffer, which must be 0-terminated. + /// The encoding object must not be deleted as long as the iterator + /// is in use. + + TextBufferIterator(const char* begin, std::size_t size, const TextEncoding& encoding); + /// Creates a TextBufferIterator for the given buffer with the given size. + /// The encoding object must not be deleted as long as the iterator + /// is in use. + + TextBufferIterator(const char* begin, const char* end, const TextEncoding& encoding); + /// Creates a TextBufferIterator for the given range. + /// The encoding object must not be deleted as long as the iterator + /// is in use. + + TextBufferIterator(const char* end); + /// Creates an end TextBufferIterator for the given buffer. + + ~TextBufferIterator(); + /// Destroys the TextBufferIterator. + + TextBufferIterator(const TextBufferIterator& it); + /// Copy constructor. + + TextBufferIterator& operator = (const TextBufferIterator& it); + /// Assignment operator. + + void swap(TextBufferIterator& it); + /// Swaps the iterator with another one. + + int operator * () const; + /// Returns the Unicode value of the current character. + /// If there is no valid character at the current position, + /// -1 is returned. + + TextBufferIterator& operator ++ (); + /// Prefix increment operator. + + TextBufferIterator operator ++ (int); + /// Postfix increment operator. + + bool operator == (const TextBufferIterator& it) const; + /// Compares two iterators for equality. + + bool operator != (const TextBufferIterator& it) const; + /// Compares two iterators for inequality. + + TextBufferIterator end() const; + /// Returns the end iterator for the range handled + /// by the iterator. + +private: + const TextEncoding* _pEncoding; + const char* _it; + const char* _end; +}; + + +// +// inlines +// +inline bool TextBufferIterator::operator == (const TextBufferIterator& it) const +{ + return _it == it._it; +} + + +inline bool TextBufferIterator::operator != (const TextBufferIterator& it) const +{ + return _it != it._it; +} + + +inline void swap(TextBufferIterator& it1, TextBufferIterator& it2) +{ + it1.swap(it2); +} + + +inline TextBufferIterator TextBufferIterator::end() const +{ + return TextBufferIterator(_end); +} + + +} // namespace Poco + + +#endif // Foundation_TextBufferIterator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TextConverter.h b/contrib/libs/poco/Foundation/include/Poco/TextConverter.h new file mode 100644 index 0000000000..ebf978fa6b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TextConverter.h @@ -0,0 +1,93 @@ +// +// TextConverter.h +// +// Library: Foundation +// Package: Text +// Module: TextConverter +// +// Definition of the TextConverter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TextConverter_INCLUDED +#define Foundation_TextConverter_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class TextEncoding; + + +class Foundation_API TextConverter + /// A TextConverter converts strings from one encoding + /// into another. +{ +public: + typedef int (*Transform)(int); + /// Transform function for convert. + + TextConverter(const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the TextConverter. The encoding objects must not be deleted while the + /// TextConverter is in use. + + ~TextConverter(); + /// Destroys the TextConverter. + + int convert(const std::string& source, std::string& destination, Transform trans); + /// Converts the source string from inEncoding to outEncoding + /// and appends the result to destination. Every character is + /// passed to the transform function. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// Returns the number of encoding errors (invalid byte sequences + /// in source). + + int convert(const void* source, int length, std::string& destination, Transform trans); + /// Converts the source buffer from inEncoding to outEncoding + /// and appends the result to destination. Every character is + /// passed to the transform function. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// Returns the number of encoding errors (invalid byte sequences + /// in source). + + int convert(const std::string& source, std::string& destination); + /// Converts the source string from inEncoding to outEncoding + /// and appends the result to destination. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// Returns the number of encoding errors (invalid byte sequences + /// in source). + + int convert(const void* source, int length, std::string& destination); + /// Converts the source buffer from inEncoding to outEncoding + /// and appends the result to destination. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// Returns the number of encoding errors (invalid byte sequences + /// in source). + +private: + TextConverter(); + TextConverter(const TextConverter&); + TextConverter& operator = (const TextConverter&); + + const TextEncoding& _inEncoding; + const TextEncoding& _outEncoding; + int _defaultChar; +}; + + +} // namespace Poco + + +#endif // Foundation_TextConverter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TextEncoding.h b/contrib/libs/poco/Foundation/include/Poco/TextEncoding.h new file mode 100644 index 0000000000..40d64b7c93 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TextEncoding.h @@ -0,0 +1,185 @@ +// +// TextEncoding.h +// +// Library: Foundation +// Package: Text +// Module: TextEncoding +// +// Definition of the abstract TextEncoding class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TextEncoding_INCLUDED +#define Foundation_TextEncoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/SharedPtr.h" + + +namespace Poco { + + +class TextEncodingManager; + + +class Foundation_API TextEncoding + /// An abstract base class for implementing text encodings + /// like UTF-8 or ISO 8859-1. + /// + /// Subclasses must override the canonicalName(), isA(), + /// characterMap() and convert() methods and need to be + /// thread safe and stateless. + /// + /// TextEncoding also provides static member functions + /// for managing mappings from encoding names to + /// TextEncoding objects. +{ +public: + typedef SharedPtr<TextEncoding> Ptr; + + enum + { + MAX_SEQUENCE_LENGTH = 4 /// The maximum character byte sequence length supported. + }; + + typedef int CharacterMap[256]; + /// The map[b] member gives information about byte sequences + /// whose first byte is b. + /// If map[b] is c where c is >= 0, then b by itself encodes the Unicode scalar value c. + /// If map[b] is -1, then the byte sequence is malformed. + /// If map[b] is -n, where n >= 2, then b is the first byte of an n-byte + /// sequence that encodes a single Unicode scalar value. Byte sequences up + /// to 4 bytes in length are supported. + + virtual ~TextEncoding(); + /// Destroys the encoding. + + virtual const char* canonicalName() const = 0; + /// Returns the canonical name of this encoding, + /// e.g. "ISO-8859-1". Encoding name comparisons are case + /// insensitive. + + virtual bool isA(const std::string& encodingName) const = 0; + /// Returns true if the given name is one of the names of this encoding. + /// For example, the "ISO-8859-1" encoding is also known as "Latin-1". + /// + /// Encoding name comparisions are case insensitive. + + virtual const CharacterMap& characterMap() const = 0; + /// Returns the CharacterMap for the encoding. + /// The CharacterMap should be kept in a static member. As + /// characterMap() can be called frequently, it should be + /// implemented in such a way that it just returns a static + /// map. If the map is built at runtime, this should be + /// done in the constructor. + + virtual int convert(const unsigned char* bytes) const; + /// The convert function is used to convert multibyte sequences; + /// bytes will point to a byte sequence of n bytes where + /// sequenceLength(bytes, length) == -n, with length >= n. + /// + /// The convert function must return the Unicode scalar value + /// represented by this byte sequence or -1 if the byte sequence is malformed. + /// + /// The default implementation returns (int) bytes[0]. + + virtual int queryConvert(const unsigned char* bytes, int length) const; + /// The queryConvert function is used to convert single byte characters + /// or multibyte sequences; + /// bytes will point to a byte sequence of length bytes. + /// + /// The queryConvert function must return the Unicode scalar value + /// represented by this byte sequence or -1 if the byte sequence is malformed + /// or -n where n is number of bytes requested for the sequence, if length is + /// shorter than the sequence. + /// The length of the sequence might not be determined by the first byte, + /// in which case the conversion becomes an iterative process: + /// First call with length == 1 might return -2, + /// Then a second call with length == 2 might return -4 + /// Eventually, the third call with length == 4 should return either a + /// Unicode scalar value, or -1 if the byte sequence is malformed. + /// + /// The default implementation returns (int) bytes[0]. + + virtual int sequenceLength(const unsigned char* bytes, int length) const; + /// The sequenceLength function is used to get the lenth of the sequence pointed + /// by bytes. The length parameter should be greater or equal to the length of + /// the sequence. + /// + /// The sequenceLength function must return the length of the sequence + /// represented by this byte sequence or a negative value -n if length is + /// shorter than the sequence, where n is the number of byte requested + /// to determine the length of the sequence. + /// The length of the sequence might not be determined by the first byte, + /// in which case the conversion becomes an iterative process as long as the + /// result is negative: + /// First call with length == 1 might return -2, + /// Then a second call with length == 2 might return -4 + /// Eventually, the third call with length == 4 should return 4. + /// The default implementation returns 1. + + virtual int convert(int ch, unsigned char* bytes, int length) const; + /// Transform the Unicode character ch into the encoding's + /// byte sequence. The method returns the number of bytes + /// used. The method must not use more than length characters. + /// Bytes and length can also be null - in this case only the number + /// of bytes required to represent ch is returned. + /// If the character cannot be converted, 0 is returned and + /// the byte sequence remains unchanged. + /// The default implementation simply returns 0. + + static TextEncoding& byName(const std::string& encodingName); + /// Returns the TextEncoding object for the given encoding name. + /// + /// Throws a NotFoundException if the encoding with given name is not available. + + static TextEncoding::Ptr find(const std::string& encodingName); + /// Returns a pointer to the TextEncoding object for the given encodingName, + /// or NULL if no such TextEncoding object exists. + + static void add(TextEncoding::Ptr encoding); + /// Adds the given TextEncoding to the table of text encodings, + /// under the encoding's canonical name. + /// + /// If an encoding with the given name is already registered, + /// it is replaced. + + static void add(TextEncoding::Ptr encoding, const std::string& name); + /// Adds the given TextEncoding to the table of text encodings, + /// under the given name. + /// + /// If an encoding with the given name is already registered, + /// it is replaced. + + static void remove(const std::string& encodingName); + /// Removes the encoding with the given name from the table + /// of text encodings. + + static TextEncoding::Ptr global(TextEncoding::Ptr encoding); + /// Sets global TextEncoding object. + /// + /// This function sets the global encoding to the argument and returns a + /// reference of the previous global encoding. + + static TextEncoding& global(); + /// Return the current global TextEncoding object + + static const std::string GLOBAL; + /// Name of the global TextEncoding, which is the empty string. + +protected: + static TextEncodingManager& manager(); + /// Returns the TextEncodingManager. +}; + + +} // namespace Poco + + +#endif // Foundation_TextEncoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TextIterator.h b/contrib/libs/poco/Foundation/include/Poco/TextIterator.h new file mode 100644 index 0000000000..17f48a4ab1 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TextIterator.h @@ -0,0 +1,141 @@ +// +// TextIterator.h +// +// Library: Foundation +// Package: Text +// Module: TextIterator +// +// Definition of the TextIterator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TextIterator_INCLUDED +#define Foundation_TextIterator_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class TextEncoding; + + +class Foundation_API TextIterator + /// An unidirectional iterator for iterating over characters in a string. + /// The TextIterator uses a TextEncoding object to + /// work with multi-byte character encodings like UTF-8. + /// Characters are reported in Unicode. + /// + /// Example: Count the number of UTF-8 characters in a string. + /// + /// UTF8Encoding utf8Encoding; + /// std::string utf8String("...."); + /// TextIterator it(utf8String, utf8Encoding); + /// TextIterator end(utf8String); + /// int n = 0; + /// while (it != end) { ++n; ++it; } + /// + /// NOTE: When an UTF-16 encoding is used, surrogate pairs will be + /// reported as two separate characters, due to restrictions of + /// the TextEncoding class. + /// + /// For iterating over char buffers, see the TextBufferIterator class. +{ +public: + TextIterator(); + /// Creates an uninitialized TextIterator. + + TextIterator(const std::string& str, const TextEncoding& encoding); + /// Creates a TextIterator for the given string. + /// The encoding object must not be deleted as long as the iterator + /// is in use. + + TextIterator(const std::string::const_iterator& begin, const std::string::const_iterator& end, const TextEncoding& encoding); + /// Creates a TextIterator for the given range. + /// The encoding object must not be deleted as long as the iterator + /// is in use. + + TextIterator(const std::string& str); + /// Creates an end TextIterator for the given string. + + TextIterator(const std::string::const_iterator& end); + /// Creates an end TextIterator. + + ~TextIterator(); + /// Destroys the TextIterator. + + TextIterator(const TextIterator& it); + /// Copy constructor. + + TextIterator& operator = (const TextIterator& it); + /// Assignment operator. + + void swap(TextIterator& it); + /// Swaps the iterator with another one. + + int operator * () const; + /// Returns the Unicode value of the current character. + /// If there is no valid character at the current position, + /// -1 is returned. + + TextIterator& operator ++ (); + /// Prefix increment operator. + + TextIterator operator ++ (int); + /// Postfix increment operator. + + bool operator == (const TextIterator& it) const; + /// Compares two iterators for equality. + + bool operator != (const TextIterator& it) const; + /// Compares two iterators for inequality. + + TextIterator end() const; + /// Returns the end iterator for the range handled + /// by the iterator. + +private: + const TextEncoding* _pEncoding; + std::string::const_iterator _it; + std::string::const_iterator _end; +}; + + +// +// inlines +// +inline bool TextIterator::operator == (const TextIterator& it) const +{ + return _it == it._it; +} + + +inline bool TextIterator::operator != (const TextIterator& it) const +{ + return _it != it._it; +} + + +inline void swap(TextIterator& it1, TextIterator& it2) +{ + it1.swap(it2); +} + + +inline TextIterator TextIterator::end() const +{ + return TextIterator(_end); +} + + +} // namespace Poco + + +#endif // Foundation_TextIterator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Thread.h b/contrib/libs/poco/Foundation/include/Poco/Thread.h new file mode 100644 index 0000000000..bfd6f031fd --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Thread.h @@ -0,0 +1,367 @@ +// +// Thread.h +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the Thread class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Thread_INCLUDED +#define Foundation_Thread_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Event.h" +#include "Poco/Mutex.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#if defined(_WIN32_WCE) +#include "Poco/Thread_WINCE.h" +#else +#include "Poco/Thread_WIN32.h" +#endif +#elif defined(POCO_VXWORKS) +#include "Poco/Thread_VX.h" +#else +#include "Poco/Thread_POSIX.h" +#endif + + +namespace Poco { + + +class Runnable; +class ThreadLocalStorage; + + +class Foundation_API Thread: private ThreadImpl + /// This class implements a platform-independent + /// wrapper to an operating system thread. + /// + /// Every Thread object gets a unique (within + /// its process) numeric thread ID. + /// Furthermore, a thread can be assigned a name. + /// The name of a thread can be changed at any time. +{ +public: + typedef ThreadImpl::TIDImpl TID; + + using ThreadImpl::Callable; + + enum Priority + /// Thread priorities. + { + PRIO_LOWEST = PRIO_LOWEST_IMPL, /// The lowest thread priority. + PRIO_LOW = PRIO_LOW_IMPL, /// A lower than normal thread priority. + PRIO_NORMAL = PRIO_NORMAL_IMPL, /// The normal thread priority. + PRIO_HIGH = PRIO_HIGH_IMPL, /// A higher than normal thread priority. + PRIO_HIGHEST = PRIO_HIGHEST_IMPL /// The highest thread priority. + }; + + enum Policy + { + POLICY_DEFAULT = POLICY_DEFAULT_IMPL + }; + + Thread(); + /// Creates a thread. Call start() to start it. + + Thread(const std::string& name); + /// Creates a named thread. Call start() to start it. + + ~Thread(); + /// Destroys the thread. + + int id() const; + /// Returns the unique thread ID of the thread. + + TID tid() const; + /// Returns the native thread ID of the thread. + + std::string name() const; + /// Returns the name of the thread. + + std::string getName() const; + /// Returns the name of the thread. + + void setName(const std::string& name); + /// Sets the name of the thread. + + void setPriority(Priority prio); + /// Sets the thread's priority. + /// + /// Some platform only allow changing a thread's priority + /// if the process has certain privileges. + + Priority getPriority() const; + /// Returns the thread's priority. + + void setOSPriority(int prio, int policy = POLICY_DEFAULT); + /// Sets the thread's priority, using an operating system specific + /// priority value. Use getMinOSPriority() and getMaxOSPriority() to + /// obtain mininum and maximum priority values. Additionally, + /// a scheduling policy can be specified. The policy is currently + /// only used on POSIX platforms where the values SCHED_OTHER (default), + /// SCHED_FIFO and SCHED_RR are supported. + + int getOSPriority() const; + /// Returns the thread's priority, expressed as an operating system + /// specific priority value. + /// + /// May return 0 if the priority has not been explicitly set. + + static int getMinOSPriority(int policy = POLICY_DEFAULT); + /// Returns the minimum operating system-specific priority value, + /// which can be passed to setOSPriority() for the given policy. + + static int getMaxOSPriority(int policy = POLICY_DEFAULT); + /// Returns the maximum operating system-specific priority value, + /// which can be passed to setOSPriority() for the given policy. + + void setStackSize(int size); + /// Sets the thread's stack size in bytes. + /// Setting the stack size to 0 will use the default stack size. + /// Typically, the real stack size is rounded up to the nearest + /// page size multiple. + + int getStackSize() const; + /// Returns the thread's stack size in bytes. + /// If the default stack size is used, 0 is returned. + + void start(Runnable& target); + /// Starts the thread with the given target. + /// + /// Note that the given Runnable object must remain + /// valid during the entire lifetime of the thread, as + /// only a reference to it is stored internally. + + void start(Callable target, void* pData = 0); + /// Starts the thread with the given target and parameter. + + template <class Functor> + void startFunc(Functor fn) + /// Starts the thread with the given functor object or lambda. + { + startImpl(new FunctorRunnable<Functor>(fn)); + } + + void join(); + /// Waits until the thread completes execution. + /// If multiple threads try to join the same + /// thread, the result is undefined. + + void join(long milliseconds); + /// Waits for at most the given interval for the thread + /// to complete. Throws a TimeoutException if the thread + /// does not complete within the specified time interval. + + bool tryJoin(long milliseconds); + /// Waits for at most the given interval for the thread + /// to complete. Returns true if the thread has finished, + /// false otherwise. + + bool isRunning() const; + /// Returns true if the thread is running. + + static bool trySleep(long milliseconds); + /// Starts an interruptible sleep. When trySleep() is called, + /// the thread will remain suspended until: + /// - the timeout expires or + /// - wakeUp() is called + /// + /// Function returns true if sleep attempt was completed, false + /// if sleep was interrupted by a wakeUp() call. + /// A frequent scenario where trySleep()/wakeUp() pair of functions + /// is useful is with threads spending most of the time idle, + /// with periodic activity between the idle times; trying to sleep + /// (as opposed to sleeping) allows immediate ending of idle thread + /// from the outside. + /// + /// The trySleep() and wakeUp() calls should be used with + /// understanding that the suspended state is not a true sleep, + /// but rather a state of waiting for an event, with timeout + /// expiration. This makes order of calls significant; calling + /// wakeUp() before calling trySleep() will prevent the next + /// trySleep() call to actually suspend the thread (which, in + /// some scenarios, may be desirable behavior). + + void wakeUp(); + /// Wakes up the thread which is in the state of interruptible + /// sleep. For threads that are not suspended, calling this + /// function has the effect of preventing the subsequent + /// trySleep() call to put thread in a suspended state. + + static void sleep(long milliseconds); + /// Suspends the current thread for the specified + /// amount of time. + + static void yield(); + /// Yields cpu to other threads. + + static Thread* current(); + /// Returns the Thread object for the currently active thread. + /// If the current thread is the main thread, 0 is returned. + + static TID currentTid(); + /// Returns the native thread ID for the current thread. + +protected: + ThreadLocalStorage& tls(); + /// Returns a reference to the thread's local storage. + + void clearTLS(); + /// Clears the thread's local storage. + + std::string makeName(); + /// Creates a unique name for a thread. + + static int uniqueId(); + /// Creates and returns a unique id for a thread. + + template <class Functor> + class FunctorRunnable: public Runnable + { + public: + FunctorRunnable(const Functor& functor): + _functor(functor) + { + } + + ~FunctorRunnable() + { + } + + void run() + { + _functor(); + } + + private: + Functor _functor; + }; + +private: + Thread(const Thread&); + Thread& operator = (const Thread&); + + int _id; + std::string _name; + ThreadLocalStorage* _pTLS; + Event _event; + mutable FastMutex _mutex; + + friend class ThreadLocalStorage; + friend class PooledThread; +}; + + +// +// inlines +// +inline Thread::TID Thread::tid() const +{ + return tidImpl(); +} + + +inline int Thread::id() const +{ + return _id; +} + + +inline std::string Thread::name() const +{ + FastMutex::ScopedLock lock(_mutex); + + return _name; +} + + +inline std::string Thread::getName() const +{ + FastMutex::ScopedLock lock(_mutex); + + return _name; +} + + +inline bool Thread::isRunning() const +{ + return isRunningImpl(); +} + + +inline void Thread::sleep(long milliseconds) +{ + sleepImpl(milliseconds); +} + + +inline void Thread::yield() +{ + yieldImpl(); +} + + +inline Thread* Thread::current() +{ + return static_cast<Thread*>(currentImpl()); +} + + +inline void Thread::setOSPriority(int prio, int policy) +{ + setOSPriorityImpl(prio, policy); +} + + +inline int Thread::getOSPriority() const +{ + return getOSPriorityImpl(); +} + + +inline int Thread::getMinOSPriority(int policy) +{ + return ThreadImpl::getMinOSPriorityImpl(policy); +} + + +inline int Thread::getMaxOSPriority(int policy) +{ + return ThreadImpl::getMaxOSPriorityImpl(policy); +} + + +inline void Thread::setStackSize(int size) +{ + setStackSizeImpl(size); +} + + +inline int Thread::getStackSize() const +{ + return getStackSizeImpl(); +} + + +inline Thread::TID Thread::currentTid() +{ + return currentTidImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_Thread_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ThreadLocal.h b/contrib/libs/poco/Foundation/include/Poco/ThreadLocal.h new file mode 100644 index 0000000000..cea17d5c12 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ThreadLocal.h @@ -0,0 +1,157 @@ +// +// ThreadLocal.h +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the ThreadLocal template and related classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ThreadLocal_INCLUDED +#define Foundation_ThreadLocal_INCLUDED + + +#include "Poco/Foundation.h" +#include <map> + + +namespace Poco { + + +class Foundation_API TLSAbstractSlot + /// This is the base class for all objects + /// that the ThreadLocalStorage class manages. +{ +public: + TLSAbstractSlot(); + virtual ~TLSAbstractSlot(); +}; + + +template <class C> +class TLSSlot: public TLSAbstractSlot + /// The Slot template wraps another class + /// so that it can be stored in a ThreadLocalStorage + /// object. This class is used internally, and you + /// must not create instances of it yourself. +{ +public: + TLSSlot(): + _value() + { + } + + ~TLSSlot() + { + } + + C& value() + { + return _value; + } + +private: + TLSSlot(const TLSSlot&); + TLSSlot& operator = (const TLSSlot&); + + C _value; +}; + + +class Foundation_API ThreadLocalStorage + /// This class manages the local storage for each thread. + /// Never use this class directly, always use the + /// ThreadLocal template for managing thread local storage. +{ +public: + ThreadLocalStorage(); + /// Creates the TLS. + + ~ThreadLocalStorage(); + /// Deletes the TLS. + + TLSAbstractSlot*& get(const void* key); + /// Returns the slot for the given key. + + static ThreadLocalStorage& current(); + /// Returns the TLS object for the current thread + /// (which may also be the main thread). + + static void clear(); + /// Clears the current thread's TLS object. + /// Does nothing in the main thread. + +private: + typedef std::map<const void*, TLSAbstractSlot*> TLSMap; + + TLSMap _map; + + friend class Thread; +}; + + +template <class C> +class ThreadLocal + /// This template is used to declare type safe thread + /// local variables. It can basically be used like + /// a smart pointer class with the special feature + /// that it references a different object + /// in every thread. The underlying object will + /// be created when it is referenced for the first + /// time. + /// See the NestedDiagnosticContext class for an + /// example how to use this template. + /// Every thread only has access to its own + /// thread local data. There is no way for a thread + /// to access another thread's local data. +{ + typedef TLSSlot<C> Slot; + +public: + ThreadLocal() + { + } + + ~ThreadLocal() + { + } + + C* operator -> () + { + return &get(); + } + + C& operator * () + /// "Dereferences" the smart pointer and returns a reference + /// to the underlying data object. The reference can be used + /// to modify the object. + { + return get(); + } + + C& get() + /// Returns a reference to the underlying data object. + /// The reference can be used to modify the object. + { + TLSAbstractSlot*& p = ThreadLocalStorage::current().get(this); + if (!p) p = new Slot; + return static_cast<Slot*>(p)->value(); + } + +private: + ThreadLocal(const ThreadLocal&); + ThreadLocal& operator = (const ThreadLocal&); +}; + + +} // namespace Poco + + +#endif // Foundation_ThreadLocal_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ThreadPool.h b/contrib/libs/poco/Foundation/include/Poco/ThreadPool.h new file mode 100644 index 0000000000..fa8bc6cf5c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ThreadPool.h @@ -0,0 +1,208 @@ +// +// ThreadPool.h +// +// Library: Foundation +// Package: Threading +// Module: ThreadPool +// +// Definition of the ThreadPool class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ThreadPool_INCLUDED +#define Foundation_ThreadPool_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Thread.h" +#include "Poco/Mutex.h" +#include <vector> + + +namespace Poco { + + +class Runnable; +class PooledThread; + + +class Foundation_API ThreadPool + /// A thread pool always keeps a number of threads running, ready + /// to accept work. + /// Creating and starting a threads can impose a significant runtime + /// overhead to an application. A thread pool helps to improve + /// the performance of an application by reducing the number + /// of threads that have to be created (and destroyed again). + /// Threads in a thread pool are re-used once they become + /// available again. + /// The thread pool always keeps a minimum number of threads + /// running. If the demans for threads increases, additional + /// threads are created. Once the demand for threads sinks + /// again, no-longer used threads are stopped and removed + /// from the pool. +{ +public: + ThreadPool(int minCapacity = 2, + int maxCapacity = 16, + int idleTime = 60, + int stackSize = POCO_THREAD_STACK_SIZE); + /// Creates a thread pool with minCapacity threads. + /// If required, up to maxCapacity threads are created + /// a NoThreadAvailableException exception is thrown. + /// If a thread is running idle for more than idleTime seconds, + /// and more than minCapacity threads are running, the thread + /// is killed. Threads are created with given stack size. + + ThreadPool(const std::string& name, + int minCapacity = 2, + int maxCapacity = 16, + int idleTime = 60, + int stackSize = POCO_THREAD_STACK_SIZE); + /// Creates a thread pool with the given name and minCapacity threads. + /// If required, up to maxCapacity threads are created + /// a NoThreadAvailableException exception is thrown. + /// If a thread is running idle for more than idleTime seconds, + /// and more than minCapacity threads are running, the thread + /// is killed. Threads are created with given stack size. + + ~ThreadPool(); + /// Currently running threads will remain active + /// until they complete. + + void addCapacity(int n); + /// Increases (or decreases, if n is negative) + /// the maximum number of threads. + + int capacity() const; + /// Returns the maximum capacity of threads. + + void setStackSize(int stackSize); + /// Sets the stack size for threads. + /// New stack size applies only for newly created threads. + + int getStackSize() const; + /// Returns the stack size used to create new threads. + + int used() const; + /// Returns the number of currently used threads. + + int allocated() const; + /// Returns the number of currently allocated threads. + + int available() const; + /// Returns the number available threads. + + void start(Runnable& target); + /// Obtains a thread and starts the target. + /// Throws a NoThreadAvailableException if no more + /// threads are available. + + void start(Runnable& target, const std::string& name); + /// Obtains a thread and starts the target. + /// Assigns the given name to the thread. + /// Throws a NoThreadAvailableException if no more + /// threads are available. + + void startWithPriority(Thread::Priority priority, Runnable& target); + /// Obtains a thread, adjusts the thread's priority, and starts the target. + /// Throws a NoThreadAvailableException if no more + /// threads are available. + + void startWithPriority(Thread::Priority priority, Runnable& target, const std::string& name); + /// Obtains a thread, adjusts the thread's priority, and starts the target. + /// Assigns the given name to the thread. + /// Throws a NoThreadAvailableException if no more + /// threads are available. + + void stopAll(); + /// Stops all running threads and waits for their completion. + /// + /// Will also delete all thread objects. + /// If used, this method should be the last action before + /// the thread pool is deleted. + /// + /// Note: If a thread fails to stop within 10 seconds + /// (due to a programming error, for example), the + /// underlying thread object will not be deleted and + /// this method will return anyway. This allows for a + /// more or less graceful shutdown in case of a misbehaving + /// thread. + + void joinAll(); + /// Waits for all threads to complete. + /// + /// Note that this will not actually join() the underlying + /// thread, but rather wait for the thread's runnables + /// to finish. + + void collect(); + /// Stops and removes no longer used threads from the + /// thread pool. Can be called at various times in an + /// application's life time to help the thread pool + /// manage its threads. Calling this method is optional, + /// as the thread pool is also implicitly managed in + /// calls to start(), addCapacity() and joinAll(). + + const std::string& name() const; + /// Returns the name of the thread pool, + /// or an empty string if no name has been + /// specified in the constructor. + + static ThreadPool& defaultPool(); + /// Returns a reference to the default + /// thread pool. + +protected: + PooledThread* getThread(); + PooledThread* createThread(); + + void housekeep(); + +private: + ThreadPool(const ThreadPool& pool); + ThreadPool& operator = (const ThreadPool& pool); + + typedef std::vector<PooledThread*> ThreadVec; + + std::string _name; + int _minCapacity; + int _maxCapacity; + int _idleTime; + int _serial; + int _age; + int _stackSize; + ThreadVec _threads; + mutable FastMutex _mutex; +}; + + +// +// inlines +// +inline void ThreadPool::setStackSize(int stackSize) +{ + _stackSize = stackSize; +} + + +inline int ThreadPool::getStackSize() const +{ + return _stackSize; +} + + +inline const std::string& ThreadPool::name() const +{ + return _name; +} + + +} // namespace Poco + + +#endif // Foundation_ThreadPool_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ThreadTarget.h b/contrib/libs/poco/Foundation/include/Poco/ThreadTarget.h new file mode 100644 index 0000000000..88452694c9 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ThreadTarget.h @@ -0,0 +1,87 @@ +// +// ThreadTarget.h +// +// Library: Foundation +// Package: Threading +// Module: ThreadTarget +// +// Definition of the ThreadTarget class. +// +// Copyright (c) 2008, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ThreadTarget_INCLUDED +#define Foundation_ThreadTarget_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" + + +namespace Poco { + + +class Foundation_API ThreadTarget: public Runnable + /// This adapter simplifies using static member functions as well as + /// standalone functions as targets for threads. + /// Note that it is possible to pass those entities directly to Thread::start(). + /// This adapter is provided as a convenience for higher abstraction level + /// scenarios where Runnable abstract class is used. + /// + /// For using a non-static member function as a thread target, please + /// see the RunnableAdapter class. + /// + /// Usage: + /// class MyObject + /// { + /// static void doSomething() {} + /// }; + /// ThreadTarget ra(&MyObject::doSomething); + /// Thread thr; + /// thr.start(ra); + /// + /// or: + /// + /// void doSomething() {} + /// + /// ThreadTarget ra(doSomething); + /// Thread thr; + /// thr.start(ra); +{ +public: + typedef void (*Callback)(); + + ThreadTarget(Callback method); + + ThreadTarget(const ThreadTarget& te); + + ~ThreadTarget(); + + ThreadTarget& operator = (const ThreadTarget& te); + + void run(); + +private: + ThreadTarget(); + + Callback _method; +}; + + +// +// inlines +// +inline void ThreadTarget::run() +{ + _method(); +} + + +} // namespace Poco + + +#endif // Foundation_ThreadTarget_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Thread_POSIX.h b/contrib/libs/poco/Foundation/include/Poco/Thread_POSIX.h new file mode 100644 index 0000000000..6b70907ed6 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Thread_POSIX.h @@ -0,0 +1,198 @@ +// +// Thread_POSIX.h +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the ThreadImpl class for POSIX Threads. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Thread_POSIX_INCLUDED +#define Foundation_Thread_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/SignalHandler.h" +#include "Poco/Event.h" +#include "Poco/RefCountedObject.h" +#include "Poco/AutoPtr.h" +#include "Poco/SharedPtr.h" +#include <pthread.h> +// must be limits.h (not <climits>) for PTHREAD_STACK_MIN on Solaris +#include <limits.h> +#if !defined(POCO_NO_SYS_SELECT_H) +#include <sys/select.h> +#endif +#include <errno.h> +#if defined(POCO_VXWORKS) +#include <cstring> +#endif + + +namespace Poco { + + +class Foundation_API ThreadImpl +{ +public: + typedef pthread_t TIDImpl; + typedef void (*Callable)(void*); + + enum Priority + { + PRIO_LOWEST_IMPL, + PRIO_LOW_IMPL, + PRIO_NORMAL_IMPL, + PRIO_HIGH_IMPL, + PRIO_HIGHEST_IMPL + }; + + enum Policy + { + POLICY_DEFAULT_IMPL = SCHED_OTHER + }; + + ThreadImpl(); + ~ThreadImpl(); + + TIDImpl tidImpl() const; + void setPriorityImpl(int prio); + int getPriorityImpl() const; + void setOSPriorityImpl(int prio, int policy = SCHED_OTHER); + int getOSPriorityImpl() const; + static int getMinOSPriorityImpl(int policy); + static int getMaxOSPriorityImpl(int policy); + void setStackSizeImpl(int size); + int getStackSizeImpl() const; + void startImpl(SharedPtr<Runnable> pTarget); + void joinImpl(); + bool joinImpl(long milliseconds); + bool isRunningImpl() const; + static void sleepImpl(long milliseconds); + static void yieldImpl(); + static ThreadImpl* currentImpl(); + static TIDImpl currentTidImpl(); + +protected: + static void* runnableEntry(void* pThread); + static int mapPrio(int prio, int policy = SCHED_OTHER); + static int reverseMapPrio(int osPrio, int policy = SCHED_OTHER); + +private: + class CurrentThreadHolder + { + public: + CurrentThreadHolder() + { + if (pthread_key_create(&_key, NULL)) + throw SystemException("cannot allocate thread context key"); + } + ~CurrentThreadHolder() + { + pthread_key_delete(_key); + } + ThreadImpl* get() const + { + return reinterpret_cast<ThreadImpl*>(pthread_getspecific(_key)); + } + void set(ThreadImpl* pThread) + { + pthread_setspecific(_key, pThread); + } + + private: + pthread_key_t _key; + }; + + struct ThreadData: public RefCountedObject + { + ThreadData(): + thread(0), + prio(PRIO_NORMAL_IMPL), + osPrio(), + policy(SCHED_OTHER), + done(false), + stackSize(POCO_THREAD_STACK_SIZE), + started(false), + joined(false) + { + #if defined(POCO_VXWORKS) + // This workaround is for VxWorks 5.x where + // pthread_init() won't properly initialize the thread. + std::memset(&thread, 0, sizeof(thread)); + #endif + } + + SharedPtr<Runnable> pRunnableTarget; + pthread_t thread; + int prio; + int osPrio; + int policy; + Event done; + std::size_t stackSize; + bool started; + bool joined; + }; + + AutoPtr<ThreadData> _pData; + + static CurrentThreadHolder _currentThreadHolder; + +#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS) + SignalHandler::JumpBufferVec _jumpBufferVec; + friend class SignalHandler; +#endif +}; + + +// +// inlines +// +inline int ThreadImpl::getPriorityImpl() const +{ + return _pData->prio; +} + + +inline int ThreadImpl::getOSPriorityImpl() const +{ + return _pData->osPrio; +} + + +inline bool ThreadImpl::isRunningImpl() const +{ + return !_pData->pRunnableTarget.isNull(); +} + + +inline void ThreadImpl::yieldImpl() +{ + sched_yield(); +} + + +inline int ThreadImpl::getStackSizeImpl() const +{ + return static_cast<int>(_pData->stackSize); +} + + +inline ThreadImpl::TIDImpl ThreadImpl::tidImpl() const +{ + return _pData->thread; +} + + +} // namespace Poco + + +#endif // Foundation_Thread_POSIX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Thread_VX.h b/contrib/libs/poco/Foundation/include/Poco/Thread_VX.h new file mode 100644 index 0000000000..883bdccb82 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Thread_VX.h @@ -0,0 +1,169 @@ +// +// Thread_VX.h +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the ThreadImpl class for VxWorks tasks. +// +// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Thread_VX_INCLUDED +#define Foundation_Thread_VX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/SignalHandler.h" +#include "Poco/Event.h" +#include "Poco/RefCountedObject.h" +#include "Poco/AutoPtr.h" +#include <taskLib.h> +#error #include <taskVarLib.h> + + +namespace Poco { + + +class Foundation_API ThreadImpl +{ +public: + typedef int TIDImpl; + typedef void (*Callable)(void*); + + enum Priority + { + PRIO_LOWEST_IMPL, + PRIO_LOW_IMPL, + PRIO_NORMAL_IMPL, + PRIO_HIGH_IMPL, + PRIO_HIGHEST_IMPL + }; + + enum Policy + { + POLICY_DEFAULT_IMPL = 0 + }; + + enum + { + DEFAULT_THREAD_STACK_SIZE = 65536 + }; + + struct CallbackData: public RefCountedObject + { + CallbackData(): callback(0), pData(0) + { + } + + Callable callback; + void* pData; + }; + + ThreadImpl(); + ~ThreadImpl(); + + TIDImpl tidImpl() const; + void setPriorityImpl(int prio); + int getPriorityImpl() const; + void setOSPriorityImpl(int prio, int policy = 0); + int getOSPriorityImpl() const; + static int getMinOSPriorityImpl(int policy); + static int getMaxOSPriorityImpl(int policy); + void setStackSizeImpl(int size); + int getStackSizeImpl() const; + void startImpl(Runnable& target); + void startImpl(Callable target, void* pData = 0); + + void joinImpl(); + bool joinImpl(long milliseconds); + bool isRunningImpl() const; + static void sleepImpl(long milliseconds); + static void yieldImpl(); + static ThreadImpl* currentImpl(); + static TIDImpl currentTidImpl(); + +protected: + static void runnableEntry(void* pThread, int, int, int, int, int, int, int, int, int); + static void callableEntry(void* pThread, int, int, int, int, int, int, int, int, int); + static int mapPrio(int prio); + static int reverseMapPrio(int osPrio); + + struct ThreadData: public RefCountedObject + { + ThreadData(): + pRunnableTarget(0), + pCallbackTarget(0), + task(0), + prio(PRIO_NORMAL_IMPL), + osPrio(127), + done(false), + stackSize(POCO_THREAD_STACK_SIZE) + { + } + + Runnable* pRunnableTarget; + AutoPtr<CallbackData> pCallbackTarget; + int task; + int prio; + int osPrio; + Event done; + int stackSize; + }; + +private: + AutoPtr<ThreadData> _pData; + static ThreadImpl* _pCurrent; +}; + + +// +// inlines +// +inline int ThreadImpl::getPriorityImpl() const +{ + return _pData->prio; +} + + +inline int ThreadImpl::getOSPriorityImpl() const +{ + return _pData->osPrio; +} + + +inline bool ThreadImpl::isRunningImpl() const +{ + return _pData->pRunnableTarget != 0 || + (_pData->pCallbackTarget.get() != 0 && _pData->pCallbackTarget->callback != 0); +} + + +inline void ThreadImpl::yieldImpl() +{ + taskDelay(0); +} + + +inline int ThreadImpl::getStackSizeImpl() const +{ + return _pData->stackSize; +} + + +inline ThreadImpl::TIDImpl ThreadImpl::tidImpl() const +{ + return _pData->task; +} + + +} // namespace Poco + + +#endif // Foundation_Thread_VX_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Thread_WIN32.h b/contrib/libs/poco/Foundation/include/Poco/Thread_WIN32.h new file mode 100644 index 0000000000..194b0a3b70 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Thread_WIN32.h @@ -0,0 +1,183 @@ +// +// Thread_WIN32.h +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the ThreadImpl class for WIN32. +// +// Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Thread_WIN32_INCLUDED +#define Foundation_Thread_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/SharedPtr.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API ThreadImpl +{ +public: + typedef DWORD TIDImpl; + typedef void (*Callable)(void*); + +#if defined(_DLL) + typedef DWORD (WINAPI *Entry)(LPVOID); +#else + typedef unsigned (__stdcall *Entry)(void*); +#endif + + enum Priority + { + PRIO_LOWEST_IMPL = THREAD_PRIORITY_LOWEST, + PRIO_LOW_IMPL = THREAD_PRIORITY_BELOW_NORMAL, + PRIO_NORMAL_IMPL = THREAD_PRIORITY_NORMAL, + PRIO_HIGH_IMPL = THREAD_PRIORITY_ABOVE_NORMAL, + PRIO_HIGHEST_IMPL = THREAD_PRIORITY_HIGHEST + }; + + enum Policy + { + POLICY_DEFAULT_IMPL = 0 + }; + + ThreadImpl(); + ~ThreadImpl(); + + TIDImpl tidImpl() const; + void setPriorityImpl(int prio); + int getPriorityImpl() const; + void setOSPriorityImpl(int prio, int policy = 0); + int getOSPriorityImpl() const; + static int getMinOSPriorityImpl(int policy); + static int getMaxOSPriorityImpl(int policy); + void setStackSizeImpl(int size); + int getStackSizeImpl() const; + void startImpl(SharedPtr<Runnable> pTarget); + void joinImpl(); + bool joinImpl(long milliseconds); + bool isRunningImpl() const; + static void sleepImpl(long milliseconds); + static void yieldImpl(); + static ThreadImpl* currentImpl(); + static TIDImpl currentTidImpl(); + +protected: +#if defined(_DLL) + static DWORD WINAPI runnableEntry(LPVOID pThread); +#else + static unsigned __stdcall runnableEntry(void* pThread); +#endif + + void createImpl(Entry ent, void* pData); + void threadCleanup(); + +private: + class CurrentThreadHolder + { + public: + CurrentThreadHolder(): _slot(TlsAlloc()) + { + if (_slot == TLS_OUT_OF_INDEXES) + throw SystemException("cannot allocate thread context key"); + } + ~CurrentThreadHolder() + { + TlsFree(_slot); + } + ThreadImpl* get() const + { + return reinterpret_cast<ThreadImpl*>(TlsGetValue(_slot)); + } + void set(ThreadImpl* pThread) + { + TlsSetValue(_slot, pThread); + } + + private: + DWORD _slot; + }; + + SharedPtr<Runnable> _pRunnableTarget; + HANDLE _thread; + DWORD _threadId; + int _prio; + int _stackSize; + + static CurrentThreadHolder _currentThreadHolder; +}; + + +// +// inlines +// +inline int ThreadImpl::getPriorityImpl() const +{ + return _prio; +} + + +inline int ThreadImpl::getOSPriorityImpl() const +{ + return _prio; +} + + +inline int ThreadImpl::getMinOSPriorityImpl(int /* policy */) +{ + return PRIO_LOWEST_IMPL; +} + + +inline int ThreadImpl::getMaxOSPriorityImpl(int /* policy */) +{ + return PRIO_HIGHEST_IMPL; +} + + +inline void ThreadImpl::sleepImpl(long milliseconds) +{ + Sleep(DWORD(milliseconds)); +} + + +inline void ThreadImpl::yieldImpl() +{ + Sleep(0); +} + + +inline void ThreadImpl::setStackSizeImpl(int size) +{ + _stackSize = size; +} + + +inline int ThreadImpl::getStackSizeImpl() const +{ + return _stackSize; +} + + +inline ThreadImpl::TIDImpl ThreadImpl::tidImpl() const +{ + return _threadId; +} + + +} // namespace Poco + + +#endif // Foundation_Thread_WIN32_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Thread_WINCE.h b/contrib/libs/poco/Foundation/include/Poco/Thread_WINCE.h new file mode 100644 index 0000000000..29f08aa345 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Thread_WINCE.h @@ -0,0 +1,179 @@ +// +// Thread_WINCE.h +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the ThreadImpl class for WIN32. +// +// Copyright (c) 2004-2010, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Thread_WINCE_INCLUDED +#define Foundation_Thread_WINCE_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/SharedPtr.h" +#include "Poco/UnWindows.h" + + +#if !defined(TLS_OUT_OF_INDEXES) // Windows CE 5.x does not define this +#define TLS_OUT_OF_INDEXES 0xFFFFFFFF +#endif + + +namespace Poco { + + +class Foundation_API ThreadImpl +{ +public: + typedef DWORD TIDImpl; + typedef void (*Callable)(void*); + typedef DWORD (WINAPI *Entry)(LPVOID); + + enum Priority + { + PRIO_LOWEST_IMPL = THREAD_PRIORITY_LOWEST, + PRIO_LOW_IMPL = THREAD_PRIORITY_BELOW_NORMAL, + PRIO_NORMAL_IMPL = THREAD_PRIORITY_NORMAL, + PRIO_HIGH_IMPL = THREAD_PRIORITY_ABOVE_NORMAL, + PRIO_HIGHEST_IMPL = THREAD_PRIORITY_HIGHEST + }; + + enum Policy + { + POLICY_DEFAULT_IMPL = 0 + }; + + ThreadImpl(); + ~ThreadImpl(); + + TIDImpl tidImpl() const; + void setPriorityImpl(int prio); + int getPriorityImpl() const; + void setOSPriorityImpl(int prio, int policy = 0); + int getOSPriorityImpl() const; + static int getMinOSPriorityImpl(int policy); + static int getMaxOSPriorityImpl(int policy); + void setStackSizeImpl(int size); + int getStackSizeImpl() const; + void startImpl(SharedPtr<Runnable> pTarget); + void joinImpl(); + bool joinImpl(long milliseconds); + bool isRunningImpl() const; + static void sleepImpl(long milliseconds); + static void yieldImpl(); + static ThreadImpl* currentImpl(); + static TIDImpl currentTidImpl(); + +protected: + static DWORD WINAPI runnableEntry(LPVOID pThread); + + void createImpl(Entry ent, void* pData); + void threadCleanup(); + +private: + class CurrentThreadHolder + { + public: + CurrentThreadHolder(): _slot(TlsAlloc()) + { + if (_slot == TLS_OUT_OF_INDEXES) + throw SystemException("cannot allocate thread context key"); + } + ~CurrentThreadHolder() + { + TlsFree(_slot); + } + ThreadImpl* get() const + { + return reinterpret_cast<ThreadImpl*>(TlsGetValue(_slot)); + } + void set(ThreadImpl* pThread) + { + TlsSetValue(_slot, pThread); + } + + private: + DWORD _slot; + }; + + SharedPtr<Runnable> _pRunnableTarget; + HANDLE _thread; + DWORD _threadId; + int _prio; + int _stackSize; + + static CurrentThreadHolder _currentThreadHolder; +}; + + +// +// inlines +// +inline int ThreadImpl::getPriorityImpl() const +{ + return _prio; +} + + +inline int ThreadImpl::getOSPriorityImpl() const +{ + return _prio; +} + + +inline int ThreadImpl::getMinOSPriorityImpl(int /* policy */) +{ + return PRIO_LOWEST_IMPL; +} + + +inline int ThreadImpl::getMaxOSPriorityImpl(int /* policy */) +{ + return PRIO_HIGHEST_IMPL; +} + + +inline void ThreadImpl::sleepImpl(long milliseconds) +{ + Sleep(DWORD(milliseconds)); +} + + +inline void ThreadImpl::yieldImpl() +{ + Sleep(0); +} + + +inline void ThreadImpl::setStackSizeImpl(int size) +{ + _stackSize = size; +} + + +inline int ThreadImpl::getStackSizeImpl() const +{ + return _stackSize; +} + + +inline ThreadImpl::TIDImpl ThreadImpl::tidImpl() const +{ + return _threadId; +} + + +} // namespace Poco + + +#endif // Foundation_Thread_WINCE_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TimedNotificationQueue.h b/contrib/libs/poco/Foundation/include/Poco/TimedNotificationQueue.h new file mode 100644 index 0000000000..841ace6b0a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TimedNotificationQueue.h @@ -0,0 +1,143 @@ +// +// TimedNotificationQueue.h +// +// Library: Foundation +// Package: Notifications +// Module: TimedNotificationQueue +// +// Definition of the TimedNotificationQueue class. +// +// Copyright (c) 2009, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TimedNotificationQueue_INCLUDED +#define Foundation_TimedNotificationQueue_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Notification.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" +#include "Poco/Timestamp.h" +#include "Poco/Clock.h" +#include <map> + + +namespace Poco { + + +class Foundation_API TimedNotificationQueue + /// A TimedNotificationQueue object provides a way to implement timed, asynchronous + /// notifications. This is especially useful for sending notifications + /// from one thread to another, for example from a background thread to + /// the main (user interface) thread. + /// + /// The TimedNotificationQueue is quite similar to the NotificationQueue class. + /// The only difference to NotificationQueue is that each Notification is tagged + /// with a Timestamp. When inserting a Notification into the queue, the + /// Notification is inserted according to the given Timestamp, with + /// lower Timestamp values being inserted before higher ones. + /// + /// Notifications are dequeued in order of their timestamps. + /// + /// TimedNotificationQueue has some restrictions regarding multithreaded use. + /// While multiple threads may enqueue notifications, only one thread at a + /// time may dequeue notifications from the queue. + /// + /// If two threads try to dequeue a notification simultaneously, the results + /// are undefined. +{ +public: + TimedNotificationQueue(); + /// Creates the TimedNotificationQueue. + + ~TimedNotificationQueue(); + /// Destroys the TimedNotificationQueue. + + void enqueueNotification(Notification::Ptr pNotification, Timestamp timestamp); + /// Enqueues the given notification by adding it to + /// the queue according to the given timestamp. + /// Lower timestamp values are inserted before higher ones. + /// The queue takes ownership of the notification, thus + /// a call like + /// notificationQueue.enqueueNotification(new MyNotification, someTime); + /// does not result in a memory leak. + /// + /// The Timestamp is converted to an equivalent Clock value. + + void enqueueNotification(Notification::Ptr pNotification, Clock clock); + /// Enqueues the given notification by adding it to + /// the queue according to the given clock value. + /// Lower clock values are inserted before higher ones. + /// The queue takes ownership of the notification, thus + /// a call like + /// notificationQueue.enqueueNotification(new MyNotification, someTime); + /// does not result in a memory leak. + + Notification* dequeueNotification(); + /// Dequeues the next pending notification with a timestamp + /// less than or equal to the current time. + /// Returns 0 (null) if no notification is available. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + Notification* waitDequeueNotification(); + /// Dequeues the next pending notification. + /// If no notification is available, waits for a notification + /// to be enqueued. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + Notification* waitDequeueNotification(long milliseconds); + /// Dequeues the next pending notification. + /// If no notification is available, waits for a notification + /// to be enqueued up to the specified time. + /// Returns 0 (null) if no notification is available. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// + /// It is highly recommended that the result is immediately + /// assigned to a Notification::Ptr, to avoid potential + /// memory management issues. + + bool empty() const; + /// Returns true iff the queue is empty. + + int size() const; + /// Returns the number of notifications in the queue. + + void clear(); + /// Removes all notifications from the queue. + /// + /// Calling clear() while another thread executes one of + /// the dequeue member functions will result in undefined + /// behavior. + +protected: + typedef std::multimap<Clock, Notification::Ptr> NfQueue; + Notification::Ptr dequeueOne(NfQueue::iterator& it); + bool wait(Clock::ClockDiff interval); + +private: + NfQueue _nfQueue; + Event _nfAvailable; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_TimedNotificationQueue_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Timer.h b/contrib/libs/poco/Foundation/include/Poco/Timer.h new file mode 100644 index 0000000000..d9f7fc2563 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Timer.h @@ -0,0 +1,229 @@ +// +// Timer.h +// +// Library: Foundation +// Package: Threading +// Module: Timer +// +// Definition of the Timer and related classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Timer_INCLUDED +#define Foundation_Timer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" +#include "Poco/Thread.h" +#include "Poco/Clock.h" + + +namespace Poco { + + +class AbstractTimerCallback; +class ThreadPool; + + +class Foundation_API Timer: protected Runnable + /// This class implements a thread-based timer. + /// A timer starts a thread that first waits for a given start interval. + /// Once that interval expires, the timer callback is called repeatedly + /// in the given periodic interval. If the interval is 0, the timer is only + /// called once. + /// The timer callback method can stop the timer by setting the + /// timer's periodic interval to 0. + /// + /// The timer callback runs in its own thread, so multithreading + /// issues (proper synchronization) have to be considered when writing + /// the callback method. + /// + /// The exact interval at which the callback is called depends on many + /// factors like operating system, CPU performance and system load and + /// may differ from the specified interval. + /// + /// The time needed to execute the timer callback is not included + /// in the interval between invocations. For example, if the interval + /// is 500 milliseconds, and the callback needs 400 milliseconds to + /// execute, the callback function is nevertheless called every 500 + /// milliseconds. If the callback takes longer to execute than the + /// interval, the callback function will not be called until the next + /// proper interval. The number of skipped invocations since the last + /// invocation will be recorded and can be obtained by the callback + /// by calling skipped(). + /// + /// The timer thread is taken from a thread pool, so + /// there is a limit to the number of available concurrent timers. +{ +public: + Timer(long startInterval = 0, long periodicInterval = 0); + /// Creates a new timer object. StartInterval and periodicInterval + /// are given in milliseconds. If a periodicInterval of zero is + /// specified, the callback will only be called once, after the + /// startInterval expires. + /// To start the timer, call the Start() method. + + virtual ~Timer(); + /// Stops and destroys the timer. + + void start(const AbstractTimerCallback& method); + /// Starts the timer. + /// Create the TimerCallback as follows: + /// TimerCallback<MyClass> callback(*this, &MyClass::onTimer); + /// timer.start(callback); + /// + /// The timer thread is taken from the global default thread pool. + + void start(const AbstractTimerCallback& method, Thread::Priority priority); + /// Starts the timer in a thread with the given priority. + /// Create the TimerCallback as follows: + /// TimerCallback<MyClass> callback(*this, &MyClass::onTimer); + /// timer.start(callback); + /// + /// The timer thread is taken from the global default thread pool. + + void start(const AbstractTimerCallback& method, ThreadPool& threadPool); + /// Starts the timer. + /// Create the TimerCallback as follows: + /// TimerCallback<MyClass> callback(*this, &MyClass::onTimer); + /// timer.start(callback); + + void start(const AbstractTimerCallback& method, Thread::Priority priority, ThreadPool& threadPool); + /// Starts the timer in a thread with the given priority. + /// Create the TimerCallback as follows: + /// TimerCallback<MyClass> callback(*this, &MyClass::onTimer); + /// timer.start(callback); + + void stop(); + /// Stops the timer. If the callback method is currently running + /// it will be allowed to finish first. + /// WARNING: Never call this method from within the callback method, + /// as a deadlock would result. To stop the timer from within the + /// callback method, call restart(0). + + void restart(); + /// Restarts the periodic interval. If the callback method is already running, + /// nothing will happen. + + void restart(long milliseconds); + /// Sets a new periodic interval and restarts the timer. + /// An interval of 0 will stop the timer. + + long getStartInterval() const; + /// Returns the start interval. + + void setStartInterval(long milliseconds); + /// Sets the start interval. Will only be + /// effective before start() is called. + + long getPeriodicInterval() const; + /// Returns the periodic interval. + + void setPeriodicInterval(long milliseconds); + /// Sets the periodic interval. If the timer is already running + /// the new interval will be effective when the current interval + /// expires. + + long skipped() const; + /// Returns the number of skipped invocations since the last invocation. + /// Skipped invocations happen if the timer callback function takes + /// longer to execute than the timer interval. + +protected: + void run(); + +private: + volatile long _startInterval; + volatile long _periodicInterval; + Event _wakeUp; + Event _done; + long _skipped; + AbstractTimerCallback* _pCallback; + Clock _nextInvocation; + mutable FastMutex _mutex; + + Timer(const Timer&); + Timer& operator = (const Timer&); +}; + + +class Foundation_API AbstractTimerCallback + /// This is the base class for all instantiations of + /// the TimerCallback template. +{ +public: + AbstractTimerCallback(); + AbstractTimerCallback(const AbstractTimerCallback& callback); + virtual ~AbstractTimerCallback(); + + AbstractTimerCallback& operator = (const AbstractTimerCallback& callback); + + virtual void invoke(Timer& timer) const = 0; + virtual AbstractTimerCallback* clone() const = 0; +}; + + +template <class C> +class TimerCallback: public AbstractTimerCallback + /// This template class implements an adapter that sits between + /// a Timer and an object's method invoked by the timer. + /// It is quite similar in concept to the RunnableAdapter, but provides + /// some Timer specific additional methods. + /// See the Timer class for information on how + /// to use this template class. +{ +public: + typedef void (C::*Callback)(Timer&); + + TimerCallback(C& object, Callback method): _pObject(&object), _method(method) + { + } + + TimerCallback(const TimerCallback& callback): _pObject(callback._pObject), _method(callback._method) + { + } + + ~TimerCallback() + { + } + + TimerCallback& operator = (const TimerCallback& callback) + { + if (&callback != this) + { + _pObject = callback._pObject; + _method = callback._method; + } + return *this; + } + + void invoke(Timer& timer) const + { + (_pObject->*_method)(timer); + } + + AbstractTimerCallback* clone() const + { + return new TimerCallback(*this); + } + +private: + TimerCallback(); + + C* _pObject; + Callback _method; +}; + + +} // namespace Poco + + +#endif // Foundation_Timer_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Timespan.h b/contrib/libs/poco/Foundation/include/Poco/Timespan.h new file mode 100644 index 0000000000..fcd742bbff --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Timespan.h @@ -0,0 +1,303 @@ +// +// Timespan.h +// +// Library: Foundation +// Package: DateTime +// Module: Timespan +// +// Definition of the Timespan class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Timespan_INCLUDED +#define Foundation_Timespan_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API Timespan + /// A class that represents time spans up to microsecond resolution. +{ +public: + typedef Timestamp::TimeDiff TimeDiff; + + Timespan(); + /// Creates a zero Timespan. + + Timespan(TimeDiff microseconds); + /// Creates a Timespan. + + Timespan(long seconds, long microseconds); + /// Creates a Timespan. Useful for creating + /// a Timespan from a struct timeval. + + Timespan(int days, int hours, int minutes, int seconds, int microSeconds); + /// Creates a Timespan. + + Timespan(const Timespan& timespan); + /// Creates a Timespan from another one. + + ~Timespan(); + /// Destroys the Timespan. + + Timespan& operator = (const Timespan& timespan); + /// Assignment operator. + + Timespan& operator = (TimeDiff microseconds); + /// Assignment operator. + + Timespan& assign(int days, int hours, int minutes, int seconds, int microSeconds); + /// Assigns a new span. + + Timespan& assign(long seconds, long microseconds); + /// Assigns a new span. Useful for assigning + /// from a struct timeval. + + void swap(Timespan& timespan); + /// Swaps the Timespan with another one. + + bool operator == (const Timespan& ts) const; + bool operator != (const Timespan& ts) const; + bool operator > (const Timespan& ts) const; + bool operator >= (const Timespan& ts) const; + bool operator < (const Timespan& ts) const; + bool operator <= (const Timespan& ts) const; + + bool operator == (TimeDiff microSeconds) const; + bool operator != (TimeDiff microSeconds) const; + bool operator > (TimeDiff microSeconds) const; + bool operator >= (TimeDiff microSeconds) const; + bool operator < (TimeDiff microSeconds) const; + bool operator <= (TimeDiff microSeconds) const; + + Timespan operator + (const Timespan& d) const; + Timespan operator - (const Timespan& d) const; + Timespan& operator += (const Timespan& d); + Timespan& operator -= (const Timespan& d); + + Timespan operator + (TimeDiff microSeconds) const; + Timespan operator - (TimeDiff microSeconds) const; + Timespan& operator += (TimeDiff microSeconds); + Timespan& operator -= (TimeDiff microSeconds); + + int days() const; + /// Returns the number of days. + + int hours() const; + /// Returns the number of hours (0 to 23). + + int totalHours() const; + /// Returns the total number of hours. + + int minutes() const; + /// Returns the number of minutes (0 to 59). + + int totalMinutes() const; + /// Returns the total number of minutes. + + int seconds() const; + /// Returns the number of seconds (0 to 59). + + int totalSeconds() const; + /// Returns the total number of seconds. + + int milliseconds() const; + /// Returns the number of milliseconds (0 to 999). + + TimeDiff totalMilliseconds() const; + /// Returns the total number of milliseconds. + + int microseconds() const; + /// Returns the fractions of a millisecond + /// in microseconds (0 to 999). + + int useconds() const; + /// Returns the fractions of a second + /// in microseconds (0 to 999999). + + TimeDiff totalMicroseconds() const; + /// Returns the total number of microseconds. + + static const TimeDiff MILLISECONDS; /// The number of microseconds in a millisecond. + static const TimeDiff SECONDS; /// The number of microseconds in a second. + static const TimeDiff MINUTES; /// The number of microseconds in a minute. + static const TimeDiff HOURS; /// The number of microseconds in a hour. + static const TimeDiff DAYS; /// The number of microseconds in a day. + +private: + TimeDiff _span; +}; + + +// +// inlines +// +inline int Timespan::days() const +{ + return int(_span/DAYS); +} + + +inline int Timespan::hours() const +{ + return int((_span/HOURS) % 24); +} + + +inline int Timespan::totalHours() const +{ + return int(_span/HOURS); +} + + +inline int Timespan::minutes() const +{ + return int((_span/MINUTES) % 60); +} + + +inline int Timespan::totalMinutes() const +{ + return int(_span/MINUTES); +} + + +inline int Timespan::seconds() const +{ + return int((_span/SECONDS) % 60); +} + + +inline int Timespan::totalSeconds() const +{ + return int(_span/SECONDS); +} + + +inline int Timespan::milliseconds() const +{ + return int((_span/MILLISECONDS) % 1000); +} + + +inline Timespan::TimeDiff Timespan::totalMilliseconds() const +{ + return _span/MILLISECONDS; +} + + +inline int Timespan::microseconds() const +{ + return int(_span % 1000); +} + + +inline int Timespan::useconds() const +{ + return int(_span % 1000000); +} + + +inline Timespan::TimeDiff Timespan::totalMicroseconds() const +{ + return _span; +} + + +inline bool Timespan::operator == (const Timespan& ts) const +{ + return _span == ts._span; +} + + +inline bool Timespan::operator != (const Timespan& ts) const +{ + return _span != ts._span; +} + + +inline bool Timespan::operator > (const Timespan& ts) const +{ + return _span > ts._span; +} + + +inline bool Timespan::operator >= (const Timespan& ts) const +{ + return _span >= ts._span; +} + + +inline bool Timespan::operator < (const Timespan& ts) const +{ + return _span < ts._span; +} + + +inline bool Timespan::operator <= (const Timespan& ts) const +{ + return _span <= ts._span; +} + + +inline bool Timespan::operator == (TimeDiff microSeconds) const +{ + return _span == microSeconds; +} + + +inline bool Timespan::operator != (TimeDiff microSeconds) const +{ + return _span != microSeconds; +} + + +inline bool Timespan::operator > (TimeDiff microSeconds) const +{ + return _span > microSeconds; +} + + +inline bool Timespan::operator >= (TimeDiff microSeconds) const +{ + return _span >= microSeconds; +} + + +inline bool Timespan::operator < (TimeDiff microSeconds) const +{ + return _span < microSeconds; +} + + +inline bool Timespan::operator <= (TimeDiff microSeconds) const +{ + return _span <= microSeconds; +} + + +inline void swap(Timespan& s1, Timespan& s2) +{ + s1.swap(s2); +} + + +inline Timespan::~Timespan() +{ +} + + +} // namespace Poco + + +#endif // Foundation_Timespan_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Timestamp.h b/contrib/libs/poco/Foundation/include/Poco/Timestamp.h new file mode 100644 index 0000000000..3fd5d9738e --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Timestamp.h @@ -0,0 +1,277 @@ +// +// Timestamp.h +// +// Library: Foundation +// Package: DateTime +// Module: Timestamp +// +// Definition of the Timestamp class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Timestamp_INCLUDED +#define Foundation_Timestamp_INCLUDED + + +#include "Poco/Foundation.h" +#include <ctime> + + +namespace Poco { + +class Timespan; + + +class Foundation_API Timestamp + /// A Timestamp stores a monotonic* time value + /// with (theoretical) microseconds resolution. + /// Timestamps can be compared with each other + /// and simple arithmetics are supported. + /// + /// [*] Note that Timestamp values are only monotonic as + /// long as the systems's clock is monotonic as well + /// (and not, e.g. set back due to time synchronization + /// or other reasons). + /// + /// Timestamps are UTC (Coordinated Universal Time) + /// based and thus independent of the timezone + /// in effect on the system. + /// + /// The internal reference time is the Unix epoch, + /// midnight, January 1, 1970. +{ +public: + typedef Int64 TimeVal; + /// Monotonic UTC time value in microsecond resolution, + /// with base time midnight, January 1, 1970. + + typedef Int64 UtcTimeVal; + /// Monotonic UTC time value in 100 nanosecond resolution, + /// with base time midnight, October 15, 1582. + + typedef Int64 TimeDiff; + /// Difference between two TimeVal values in microseconds. + + static const TimeVal TIMEVAL_MIN; /// Minimum timestamp value. + static const TimeVal TIMEVAL_MAX; /// Maximum timestamp value. + + Timestamp(); + /// Creates a timestamp with the current time. + + Timestamp(TimeVal tv); + /// Creates a timestamp from the given time value + /// (microseconds since midnight, January 1, 1970). + + Timestamp(const Timestamp& other); + /// Copy constructor. + + ~Timestamp(); + /// Destroys the timestamp + + Timestamp& operator = (const Timestamp& other); + Timestamp& operator = (TimeVal tv); + + void swap(Timestamp& timestamp); + /// Swaps the Timestamp with another one. + + void update(); + /// Updates the Timestamp with the current time. + + bool operator == (const Timestamp& ts) const; + bool operator != (const Timestamp& ts) const; + bool operator > (const Timestamp& ts) const; + bool operator >= (const Timestamp& ts) const; + bool operator < (const Timestamp& ts) const; + bool operator <= (const Timestamp& ts) const; + + Timestamp operator + (TimeDiff d) const; + Timestamp operator + (const Timespan& span) const; + Timestamp operator - (TimeDiff d) const; + Timestamp operator - (const Timespan& span) const; + TimeDiff operator - (const Timestamp& ts) const; + Timestamp& operator += (TimeDiff d); + Timestamp& operator += (const Timespan& span); + Timestamp& operator -= (TimeDiff d); + Timestamp& operator -= (const Timespan& span); + + std::time_t epochTime() const; + /// Returns the timestamp expressed in time_t. + /// time_t base time is midnight, January 1, 1970. + /// Resolution is one second. + + UtcTimeVal utcTime() const; + /// Returns the timestamp expressed in UTC-based + /// time. UTC base time is midnight, October 15, 1582. + /// Resolution is 100 nanoseconds. + + TimeVal epochMicroseconds() const; + /// Returns the timestamp expressed in microseconds + /// since the Unix epoch, midnight, January 1, 1970. + + TimeDiff elapsed() const; + /// Returns the time elapsed since the time denoted by + /// the timestamp. Equivalent to Timestamp() - *this. + + bool isElapsed(TimeDiff interval) const; + /// Returns true iff the given interval has passed + /// since the time denoted by the timestamp. + + TimeVal raw() const; + /// Returns the raw time value. + /// + /// Same as epochMicroseconds(). + + static Timestamp fromEpochTime(std::time_t t); + /// Creates a timestamp from a std::time_t. + + static Timestamp fromUtcTime(UtcTimeVal val); + /// Creates a timestamp from a UTC time value + /// (100 nanosecond intervals since midnight, + /// October 15, 1582). + + static TimeDiff resolution(); + /// Returns the resolution in units per second. + /// Since the timestamp has microsecond resolution, + /// the returned value is always 1000000. + +#if defined(_WIN32) + static Timestamp fromFileTimeNP(UInt32 fileTimeLow, UInt32 fileTimeHigh); + void toFileTimeNP(UInt32& fileTimeLow, UInt32& fileTimeHigh) const; +#endif + +private: + TimeVal _ts; +}; + + +// +// inlines +// +inline bool Timestamp::operator == (const Timestamp& ts) const +{ + return _ts == ts._ts; +} + + +inline bool Timestamp::operator != (const Timestamp& ts) const +{ + return _ts != ts._ts; +} + + +inline bool Timestamp::operator > (const Timestamp& ts) const +{ + return _ts > ts._ts; +} + + +inline bool Timestamp::operator >= (const Timestamp& ts) const +{ + return _ts >= ts._ts; +} + + +inline bool Timestamp::operator < (const Timestamp& ts) const +{ + return _ts < ts._ts; +} + + +inline bool Timestamp::operator <= (const Timestamp& ts) const +{ + return _ts <= ts._ts; +} + + +inline Timestamp Timestamp::operator + (Timestamp::TimeDiff d) const +{ + return Timestamp(_ts + d); +} + + +inline Timestamp Timestamp::operator - (Timestamp::TimeDiff d) const +{ + return Timestamp(_ts - d); +} + + +inline Timestamp::TimeDiff Timestamp::operator - (const Timestamp& ts) const +{ + return _ts - ts._ts; +} + + +inline Timestamp& Timestamp::operator += (Timestamp::TimeDiff d) +{ + _ts += d; + return *this; +} + + +inline Timestamp& Timestamp::operator -= (Timestamp::TimeDiff d) +{ + _ts -= d; + return *this; +} + + +inline std::time_t Timestamp::epochTime() const +{ + return std::time_t(_ts/resolution()); +} + + +inline Timestamp::UtcTimeVal Timestamp::utcTime() const +{ + return _ts*10 + (TimeDiff(0x01b21dd2) << 32) + 0x13814000; +} + + +inline Timestamp::TimeVal Timestamp::epochMicroseconds() const +{ + return _ts; +} + + +inline Timestamp::TimeDiff Timestamp::elapsed() const +{ + Timestamp now; + return now - *this; +} + + +inline bool Timestamp::isElapsed(Timestamp::TimeDiff interval) const +{ + Timestamp now; + Timestamp::TimeDiff diff = now - *this; + return diff >= interval; +} + + +inline Timestamp::TimeDiff Timestamp::resolution() +{ + return 1000000; +} + + +inline void swap(Timestamp& s1, Timestamp& s2) +{ + s1.swap(s2); +} + + +inline Timestamp::TimeVal Timestamp::raw() const +{ + return _ts; +} + + +} // namespace Poco + + +#endif // Foundation_Timestamp_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Timezone.h b/contrib/libs/poco/Foundation/include/Poco/Timezone.h new file mode 100644 index 0000000000..c273f32f5b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Timezone.h @@ -0,0 +1,67 @@ +// +// Timezone.h +// +// Library: Foundation +// Package: DateTime +// Module: Timezone +// +// Definition of the Timezone class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Timezone_INCLUDED +#define Foundation_Timezone_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API Timezone + /// This class provides information about the current timezone. +{ +public: + static int utcOffset(); + /// Returns the offset of local time to UTC, in seconds. + /// local time = UTC + utcOffset() + dst(). + + static int dst(); + /// Returns the daylight saving time offset in seconds if + /// daylight saving time is in use. + /// local time = UTC + utcOffset() + dst(). + + static bool isDst(const Timestamp& timestamp); + /// Returns true if daylight saving time is in effect + /// for the given time. Depending on the operating system + /// platform this might only work reliably for certain + /// date ranges, as the C library's localtime() function + /// is used. + + static int tzd(); + /// Returns the time zone differential for the current timezone. + /// The timezone differential is computed as utcOffset() + dst() + /// and is expressed in seconds. + + static std::string name(); + /// Returns the timezone name currently in effect. + + static std::string standardName(); + /// Returns the timezone name if not daylight saving time is in effect. + + static std::string dstName(); + /// Returns the timezone name if daylight saving time is in effect. +}; + + +} // namespace Poco + + +#endif // Foundation_Timezone_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Token.h b/contrib/libs/poco/Foundation/include/Poco/Token.h new file mode 100644 index 0000000000..13540af914 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Token.h @@ -0,0 +1,172 @@ +// +// Token.h +// +// Library: Foundation +// Package: Streams +// Module: StreamTokenizer +// +// Definition of the Token class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Token_INCLUDED +#define Foundation_Token_INCLUDED + + +#include "Poco/Foundation.h" +#include <istream> + + +namespace Poco { + + +class Foundation_API Token + /// The base class for all token classes that can be + /// registered with the StreamTokenizer. +{ +public: + enum Class + { + IDENTIFIER_TOKEN, + KEYWORD_TOKEN, + SEPARATOR_TOKEN, + OPERATOR_TOKEN, + STRING_LITERAL_TOKEN, + CHAR_LITERAL_TOKEN, + INTEGER_LITERAL_TOKEN, + LONG_INTEGER_LITERAL_TOKEN, + FLOAT_LITERAL_TOKEN, + DOUBLE_LITERAL_TOKEN, + COMMENT_TOKEN, + SPECIAL_COMMENT_TOKEN, + PREPROCESSOR_TOKEN, + WHITESPACE_TOKEN, + EOF_TOKEN, + INVALID_TOKEN, + USER_TOKEN + }; + + Token(); + /// Creates the Token. + + virtual ~Token(); + /// Destroys the Token. + + virtual bool start(char c, std::istream& istr); + /// Checks if the given character (and, optionally, + /// the next character in the input stream) start + /// a valid token. Returns true if so, false + /// otherwise. + /// + /// The current read position in istr must not be + /// changed. In other words, only the peek() method + /// of istream may be used. + /// + /// If the character starts the token, it should + /// be set as the token's value. + + virtual void finish(std::istream& istr); + /// Builds the token by reading and appending + /// the remaining characters from istr. + + virtual Class tokenClass() const; + /// Returns the kind of the token. + + const std::string& tokenString() const; + /// Returns the token's raw string. + + virtual std::string asString() const; + /// Returns a string representation of the token. + +#if defined(POCO_HAVE_INT64) + virtual Int64 asInteger64() const; + /// Returns a 64-bit integer representation of the token. + + virtual UInt64 asUnsignedInteger64() const; + /// Returns an unsigned 64-bit integer representation of the token. +#endif + + virtual int asInteger() const; + /// Returns an integer representation of the token. + + virtual unsigned asUnsignedInteger() const; + /// Returns an unsigned integer representation of the token. + + virtual double asFloat() const; + /// Returns a floating-point representation of the token. + + virtual char asChar() const; + /// Returns a char representation of the token. + + bool is(Class tokenClass) const; + /// Returns true iff the token has the given class. + +protected: + std::string _value; + +private: + Token(const Token&); + Token& operator = (const Token&); +}; + + +class Foundation_API InvalidToken: public Token + /// This token class is used for signalling that + /// an invalid character sequence has been encountered + /// in the input stream. +{ +public: + InvalidToken(); + ~InvalidToken(); + Class tokenClass() const; +}; + + +class Foundation_API EOFToken: public Token + /// This token class is used to signal the + /// end of the input stream. +{ +public: + EOFToken(); + ~EOFToken(); + Class tokenClass() const; +}; + + +class Foundation_API WhitespaceToken: public Token + /// This pseudo token class is used to eat + /// up whitespace in between real tokens. +{ +public: + WhitespaceToken(); + ~WhitespaceToken(); + Class tokenClass() const; + bool start(char c, std::istream& istr); + void finish(std::istream& istr); +}; + + +// +// inlines +// +inline const std::string& Token::tokenString() const +{ + return _value; +} + + +inline bool Token::is(Token::Class cls) const +{ + return tokenClass() == cls; +} + + +} // namespace Poco + + +#endif // Foundation_Token_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Tuple.h b/contrib/libs/poco/Foundation/include/Poco/Tuple.h new file mode 100644 index 0000000000..2111bf8a9c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Tuple.h @@ -0,0 +1,1747 @@ +// +// Tuple.h +// +// Library: Foundation +// Package: Core +// Module: Tuple +// +// Definition of the Tuple class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Tuple_INCLUDED +#define Foundation_Tuple_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TypeList.h" + + +namespace Poco { + + +#if defined(_MSC_VER) +#define POCO_TYPEWRAPPER_DEFAULTVALUE(T) TypeWrapper<T>::TYPE() +#else +#define POCO_TYPEWRAPPER_DEFAULTVALUE(T) typename TypeWrapper<T>::TYPE() +#endif + + +template <class T0, + class T1 = NullTypeList, + class T2 = NullTypeList, + class T3 = NullTypeList, + class T4 = NullTypeList, + class T5 = NullTypeList, + class T6 = NullTypeList, + class T7 = NullTypeList, + class T8 = NullTypeList, + class T9 = NullTypeList, + class T10 = NullTypeList, + class T11 = NullTypeList, + class T12 = NullTypeList, + class T13 = NullTypeList, + class T14 = NullTypeList, + class T15 = NullTypeList, + class T16 = NullTypeList, + class T17 = NullTypeList, + class T18 = NullTypeList, + class T19 = NullTypeList> +struct Tuple +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17), + typename TypeWrapper<T18>::CONSTTYPE& t18 = POCO_TYPEWRAPPER_DEFAULTVALUE(T18), + typename TypeWrapper<T19>::CONSTTYPE& t19 = POCO_TYPEWRAPPER_DEFAULTVALUE(T19)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t8, typename TypeListType<T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t9, typename TypeListType<T10,T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t10, typename TypeListType<T11,T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t11, typename TypeListType<T12,T13,T14,T15,T16,T17,T18,T19>::HeadType + (t12, typename TypeListType<T13,T14,T15,T16,T17,T18,T19>::HeadType + (t13, typename TypeListType<T14,T15,T16,T17,T18,T19>::HeadType + (t14, typename TypeListType<T15,T16,T17,T18,T19>::HeadType + (t15, typename TypeListType<T16,T17,T18,T19>::HeadType + (t16, typename TypeListType<T17,T18,T19>::HeadType + (t17, typename TypeListType<T18,T19>::HeadType + (t18, typename TypeListType<T19>::HeadType + (t19, NullTypeList())))))))))))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14, + class T15, + class T16, + class T17, + class T18> +struct Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17), + typename TypeWrapper<T18>::CONSTTYPE& t18 = POCO_TYPEWRAPPER_DEFAULTVALUE(T18)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t8, typename TypeListType<T9,T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t9, typename TypeListType<T10,T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t10, typename TypeListType<T11,T12,T13,T14,T15,T16,T17,T18>::HeadType + (t11, typename TypeListType<T12,T13,T14,T15,T16,T17,T18>::HeadType + (t12, typename TypeListType<T13,T14,T15,T16,T17,T18>::HeadType + (t13, typename TypeListType<T14,T15,T16,T17,T18>::HeadType + (t14, typename TypeListType<T15,T16,T17,T18>::HeadType + (t15, typename TypeListType<T16,T17,T18>::HeadType + (t16, typename TypeListType<T17,T18>::HeadType + (t17, typename TypeListType<T18>::HeadType + (t18, NullTypeList()))))))))))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14, + class T15, + class T16, + class T17> +struct Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16), + typename TypeWrapper<T17>::CONSTTYPE& t17 = POCO_TYPEWRAPPER_DEFAULTVALUE(T17)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t8, typename TypeListType<T9,T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t9, typename TypeListType<T10,T11,T12,T13,T14,T15,T16,T17>::HeadType + (t10, typename TypeListType<T11,T12,T13,T14,T15,T16,T17>::HeadType + (t11, typename TypeListType<T12,T13,T14,T15,T16,T17>::HeadType + (t12, typename TypeListType<T13,T14,T15,T16,T17>::HeadType + (t13, typename TypeListType<T14,T15,T16,T17>::HeadType + (t14, typename TypeListType<T15,T16,T17>::HeadType + (t15, typename TypeListType<T16,T17>::HeadType + (t16, typename TypeListType<T17>::HeadType + (t17, NullTypeList())))))))))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14, + class T15, + class T16> +struct Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15), + typename TypeWrapper<T16>::CONSTTYPE& t16 = POCO_TYPEWRAPPER_DEFAULTVALUE(T16)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t8, typename TypeListType<T9,T10,T11,T12,T13,T14,T15,T16>::HeadType + (t9, typename TypeListType<T10,T11,T12,T13,T14,T15,T16>::HeadType + (t10, typename TypeListType<T11,T12,T13,T14,T15,T16>::HeadType + (t11, typename TypeListType<T12,T13,T14,T15,T16>::HeadType + (t12, typename TypeListType<T13,T14,T15,T16>::HeadType + (t13, typename TypeListType<T14,T15,T16>::HeadType + (t14, typename TypeListType<T15,T16>::HeadType + (t15, typename TypeListType<T16>::HeadType + (t16, NullTypeList()))))))))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14, + class T15> +struct Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14), + typename TypeWrapper<T15>::CONSTTYPE& t15 = POCO_TYPEWRAPPER_DEFAULTVALUE(T15)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11,T12,T13,T14,T15>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11,T12,T13,T14,T15>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11,T12,T13,T14,T15>::HeadType + (t8, typename TypeListType<T9,T10,T11,T12,T13,T14,T15>::HeadType + (t9, typename TypeListType<T10,T11,T12,T13,T14,T15>::HeadType + (t10, typename TypeListType<T11,T12,T13,T14,T15>::HeadType + (t11, typename TypeListType<T12,T13,T14,T15>::HeadType + (t12, typename TypeListType<T13,T14,T15>::HeadType + (t13, typename TypeListType<T14,T15>::HeadType + (t14, typename TypeListType<T15>::HeadType + (t15, NullTypeList())))))))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13, + class T14> +struct Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13), + typename TypeWrapper<T14>::CONSTTYPE& t14 = POCO_TYPEWRAPPER_DEFAULTVALUE(T14)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11,T12,T13,T14>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11,T12,T13,T14>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11,T12,T13,T14>::HeadType + (t8, typename TypeListType<T9,T10,T11,T12,T13,T14>::HeadType + (t9, typename TypeListType<T10,T11,T12,T13,T14>::HeadType + (t10, typename TypeListType<T11,T12,T13,T14>::HeadType + (t11, typename TypeListType<T12,T13,T14>::HeadType + (t12, typename TypeListType<T13,T14>::HeadType + (t13, typename TypeListType<T14>::HeadType + (t14, NullTypeList()))))))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12, + class T13> +struct Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12), + typename TypeWrapper<T13>::CONSTTYPE& t13 = POCO_TYPEWRAPPER_DEFAULTVALUE(T13)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11,T12,T13>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11,T12,T13>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11,T12,T13>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11,T12,T13>::HeadType + (t8, typename TypeListType<T9,T10,T11,T12,T13>::HeadType + (t9, typename TypeListType<T10,T11,T12,T13>::HeadType + (t10, typename TypeListType<T11,T12,T13>::HeadType + (t11, typename TypeListType<T12,T13>::HeadType + (t12, typename TypeListType<T13>::HeadType + (t13, NullTypeList())))))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11, + class T12> +struct Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11), + typename TypeWrapper<T12>::CONSTTYPE& t12 = POCO_TYPEWRAPPER_DEFAULTVALUE(T12)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11,T12>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11,T12>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11,T12>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11,T12>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11,T12>::HeadType + (t8, typename TypeListType<T9,T10,T11,T12>::HeadType + (t9, typename TypeListType<T10,T11,T12>::HeadType + (t10, typename TypeListType<T11,T12>::HeadType + (t11, typename TypeListType<T12>::HeadType + (t12, NullTypeList()))))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10, + class T11> +struct Tuple<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10), + typename TypeWrapper<T11>::CONSTTYPE& t11 = POCO_TYPEWRAPPER_DEFAULTVALUE(T11)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10,T11>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10,T11>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10,T11>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10,T11>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10,T11>::HeadType + (t7, typename TypeListType<T8,T9,T10,T11>::HeadType + (t8, typename TypeListType<T9,T10,T11>::HeadType + (t9, typename TypeListType<T10,T11>::HeadType + (t10, typename TypeListType<T11>::HeadType + (t11, NullTypeList())))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9, + class T10> +struct Tuple<T0, T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9), + typename TypeWrapper<T10>::CONSTTYPE& t10 = POCO_TYPEWRAPPER_DEFAULTVALUE(T10)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9,T10>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9,T10>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9,T10>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9,T10>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9,T10>::HeadType + (t6, typename TypeListType<T7,T8,T9,T10>::HeadType + (t7, typename TypeListType<T8,T9,T10>::HeadType + (t8, typename TypeListType<T9,T10>::HeadType + (t9, typename TypeListType<T10>::HeadType + (t10, NullTypeList()))))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8, + class T9> +struct Tuple<T0, T1,T2,T3,T4,T5,T6,T7,T8,T9, NullTypeList> +{ + typedef typename TypeListType<T0, T1,T2,T3,T4,T5,T6,T7,T8,T9>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8), + typename TypeWrapper<T9>::CONSTTYPE& t9 = POCO_TYPEWRAPPER_DEFAULTVALUE(T9)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8,T9>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8,T9>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8,T9>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8,T9>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8,T9>::HeadType + (t5, typename TypeListType<T6,T7,T8,T9>::HeadType + (t6, typename TypeListType<T7,T8,T9>::HeadType + (t7, typename TypeListType<T8,T9>::HeadType + (t8, typename TypeListType<T9>::HeadType + (t9, NullTypeList())))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7, + class T8> +struct Tuple<T0, T1,T2,T3,T4,T5,T6,T7,T8, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7,T8>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7), + typename TypeWrapper<T8>::CONSTTYPE& t8 = POCO_TYPEWRAPPER_DEFAULTVALUE(T8)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7,T8>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7,T8>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7,T8>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7,T8>::HeadType + (t4, typename TypeListType<T5,T6,T7,T8>::HeadType + (t5, typename TypeListType<T6,T7,T8>::HeadType + (t6, typename TypeListType<T7,T8>::HeadType + (t7, typename TypeListType<T8>::HeadType + (t8, NullTypeList()))))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6, + class T7> +struct Tuple<T0, T1,T2,T3,T4,T5,T6,T7, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6,T7>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6), + typename TypeWrapper<T7>::CONSTTYPE& t7 = POCO_TYPEWRAPPER_DEFAULTVALUE(T7)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6,T7>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6,T7>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6,T7>::HeadType + (t3, typename TypeListType<T4,T5,T6,T7>::HeadType + (t4, typename TypeListType<T5,T6,T7>::HeadType + (t5, typename TypeListType<T6,T7>::HeadType + (t6, typename TypeListType<T7>::HeadType + (t7, NullTypeList())))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5, + class T6> +struct Tuple<T0, T1,T2,T3,T4,T5,T6, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5,T6>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5), + typename TypeWrapper<T6>::CONSTTYPE& t6 = POCO_TYPEWRAPPER_DEFAULTVALUE(T6)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5,T6>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5,T6>::HeadType + (t2, typename TypeListType<T3,T4,T5,T6>::HeadType + (t3, typename TypeListType<T4,T5,T6>::HeadType + (t4, typename TypeListType<T5,T6>::HeadType + (t5, typename TypeListType<T6>::HeadType + (t6, NullTypeList()))))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4, + class T5> +struct Tuple<T0, T1,T2,T3,T4,T5, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4,T5>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4), + typename TypeWrapper<T5>::CONSTTYPE& t5 = POCO_TYPEWRAPPER_DEFAULTVALUE(T5)): + _data(t0, typename TypeListType<T1,T2,T3,T4,T5>::HeadType + (t1, typename TypeListType<T2,T3,T4,T5>::HeadType + (t2, typename TypeListType<T3,T4,T5>::HeadType + (t3, typename TypeListType<T4,T5>::HeadType + (t4, typename TypeListType<T5>::HeadType + (t5, NullTypeList())))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3, + class T4> +struct Tuple<T0, T1,T2,T3,T4, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3,T4>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3), + typename TypeWrapper<T4>::CONSTTYPE& t4 = POCO_TYPEWRAPPER_DEFAULTVALUE(T4)): + _data(t0, typename TypeListType<T1,T2,T3,T4>::HeadType + (t1, typename TypeListType<T2,T3,T4>::HeadType + (t2, typename TypeListType<T3,T4>::HeadType + (t3, typename TypeListType<T4>::HeadType + (t4, NullTypeList()))))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2, + class T3> +struct Tuple<T0, T1,T2,T3, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2,T3>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2), + typename TypeWrapper<T3>::CONSTTYPE& t3 = POCO_TYPEWRAPPER_DEFAULTVALUE(T3)): + _data(t0, typename TypeListType<T1,T2,T3>::HeadType + (t1, typename TypeListType<T2,T3>::HeadType + (t2, typename TypeListType<T3>::HeadType + (t3, NullTypeList())))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1, + class T2> +struct Tuple<T0, T1,T2, NullTypeList> +{ + typedef typename TypeListType<T0,T1,T2>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1), + typename TypeWrapper<T2>::CONSTTYPE& t2 = POCO_TYPEWRAPPER_DEFAULTVALUE(T2)): + _data(t0, typename TypeListType<T1,T2>::HeadType + (t1, typename TypeListType<T2>::HeadType + (t2, NullTypeList()))) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0, + class T1> +struct Tuple<T0, T1, NullTypeList> +{ + typedef typename TypeListType<T0,T1>::HeadType Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0, + typename TypeWrapper<T1>::CONSTTYPE& t1 = POCO_TYPEWRAPPER_DEFAULTVALUE(T1)): + _data(t0, typename TypeListType<T1>::HeadType(t1, NullTypeList())) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +template <class T0> +struct Tuple<T0, NullTypeList> +{ + typedef TypeList<T0, NullTypeList> Type; + + enum TupleLengthType + { + length = Type::length + }; + + Tuple():_data() + { + } + + Tuple(typename TypeWrapper<T0>::CONSTTYPE& t0): + _data(t0, NullTypeList()) + { + } + + template <int N> + typename TypeGetter<N, Type>::ConstHeadType& get() const + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + typename TypeGetter<N, Type>::HeadType& get() + { + return Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data); + } + + template <int N> + void set(typename TypeGetter<N, Type>::ConstHeadType& val) + { + Getter<N>::template get<typename TypeGetter<N, Type>::HeadType, typename Type::HeadType, typename Type::TailType>(_data) = val; + } + + bool operator == (const Tuple& other) const + { + return _data == other._data; + } + + bool operator != (const Tuple& other) const + { + return !(_data == other._data); + } + + bool operator < (const Tuple& other) const + { + return _data < other._data; + } + +private: + Type _data; +}; + + +} // namespace Poco + + +#endif // Foundation_Tuple_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/TypeList.h b/contrib/libs/poco/Foundation/include/Poco/TypeList.h new file mode 100644 index 0000000000..352696f8e0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/TypeList.h @@ -0,0 +1,483 @@ +// +// TypeList.h +// +// Library: Foundation +// Package: Core +// Module: TypeList +// +// Implementation of the TypeList template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// Portions extracted and adapted from +// The Loki Library +// Copyright (c) 2001 by Andrei Alexandrescu +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_TypeList_INCLUDED +#define Foundation_TypeList_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/MetaProgramming.h" + + +namespace Poco { + + +template <class Head, class Tail> +struct TypeList; + + +struct NullTypeList +{ + enum + { + length = 0 + }; + + bool operator == (const NullTypeList&) const + { + return true; + } + + bool operator != (const NullTypeList&) const + { + return false; + } + + bool operator < (const NullTypeList&) const + { + return false; + } +}; + + +template <class Head, class Tail> +struct TypeList + /// Compile Time List of Types +{ + typedef Head HeadType; + typedef Tail TailType; + typedef typename TypeWrapper<HeadType>::CONSTTYPE ConstHeadType; + typedef typename TypeWrapper<TailType>::CONSTTYPE ConstTailType; + enum + { + length = TailType::length+1 + }; + + TypeList():head(), tail() + { + } + + TypeList(ConstHeadType& h, ConstTailType& t):head(h), tail(t) + { + } + + TypeList(const TypeList& tl): head(tl.head), tail(tl.tail) + { + } + + TypeList& operator = (const TypeList& tl) + { + if (this != &tl) + { + head = tl.head; + tail = tl.tail; + } + return *this; + } + + bool operator == (const TypeList& tl) const + { + return tl.head == head && tl.tail == tail; + } + + bool operator != (const TypeList& tl) const + { + return !(*this == tl); + } + + bool operator < (const TypeList& tl) const + { + if (head < tl.head) + return true; + else if (head == tl.head) + return tail < tl.tail; + return false; + } + + HeadType head; + TailType tail; +}; + + +template <typename T0 = NullTypeList, + typename T1 = NullTypeList, + typename T2 = NullTypeList, + typename T3 = NullTypeList, + typename T4 = NullTypeList, + typename T5 = NullTypeList, + typename T6 = NullTypeList, + typename T7 = NullTypeList, + typename T8 = NullTypeList, + typename T9 = NullTypeList, + typename T10 = NullTypeList, + typename T11 = NullTypeList, + typename T12 = NullTypeList, + typename T13 = NullTypeList, + typename T14 = NullTypeList, + typename T15 = NullTypeList, + typename T16 = NullTypeList, + typename T17 = NullTypeList, + typename T18 = NullTypeList, + typename T19 = NullTypeList, + typename T20 = NullTypeList, + typename T21 = NullTypeList, + typename T22 = NullTypeList, + typename T23 = NullTypeList, + typename T24 = NullTypeList, + typename T25 = NullTypeList, + typename T26 = NullTypeList, + typename T27 = NullTypeList, + typename T28 = NullTypeList, + typename T29 = NullTypeList, + typename T30 = NullTypeList, + typename T31 = NullTypeList, + typename T32 = NullTypeList, + typename T33 = NullTypeList, + typename T34 = NullTypeList, + typename T35 = NullTypeList, + typename T36 = NullTypeList, + typename T37 = NullTypeList, + typename T38 = NullTypeList, + typename T39 = NullTypeList> +struct TypeListType + /// TypeListType takes 1 - 40 typename arguments. + /// Usage: + /// + /// TypeListType<T0, T1, ... , Tn>::HeadType typeList; + /// + /// typeList is a TypeList of T0, T1, ... , Tn +{ +private: + typedef typename + TypeListType<T1,T2, T3, T4, T5, T6, T7, T8, T9, T10, + T11,T12,T13,T14,T15,T16,T17,T18,T19,T20, + T21,T22,T23,T24,T25,T26,T27,T28,T29,T30, + T31,T32,T33,T34,T35,T36,T37,T38,T39>::HeadType TailType; + +public: + typedef TypeList<T0, TailType> HeadType; +}; + + +template <> +struct TypeListType<> +{ + typedef NullTypeList HeadType; +}; + + +template <int n> +struct Getter +{ + template <class Ret, class Head, class Tail> + inline static Ret& get(TypeList<Head, Tail>& val) + { + return Getter<n-1>::template get<Ret, typename Tail::HeadType, typename Tail::TailType>(val.tail); + } + + template <class Ret, class Head, class Tail> + inline static const Ret& get(const TypeList<Head, Tail>& val) + { + return Getter<n-1>::template get<Ret, typename Tail::HeadType, typename Tail::TailType>(val.tail); + } +}; + + +template <> +struct Getter<0> +{ + template <class Ret, class Head, class Tail> + inline static Ret& get(TypeList<Head, Tail>& val) + { + return val.head; + } + + template <class Ret, class Head, class Tail> + inline static const Ret& get(const TypeList<Head, Tail>& val) + { + return val.head; + } +}; + + +template <int N, class Head> +struct TypeGetter; + + +template <int N, class Head, class Tail> +struct TypeGetter<N, TypeList<Head, Tail> > +{ + typedef typename TypeGetter<N-1, Tail>::HeadType HeadType; + typedef typename TypeWrapper<HeadType>::CONSTTYPE ConstHeadType; +}; + + +template <class Head, class Tail> +struct TypeGetter<0, TypeList<Head, Tail> > +{ + typedef typename TypeList<Head, Tail>::HeadType HeadType; + typedef typename TypeWrapper<HeadType>::CONSTTYPE ConstHeadType; +}; + + +template <class Head, class T> +struct TypeLocator; + /// TypeLocator returns the first occurrence of the type T in Head + /// or -1 if the type is not found. + /// + /// Usage example: + /// + /// TypeLocator<Head, int>::HeadType TypeLoc; + /// + /// if (2 == TypeLoc.value) ... + /// + + +template <class T> +struct TypeLocator<NullTypeList, T> +{ + enum { value = -1 }; +}; + + +template <class T, class Tail> +struct TypeLocator<TypeList<T, Tail>, T> +{ + enum { value = 0 }; +}; + + +template <class Head, class Tail, class T> +struct TypeLocator<TypeList<Head, Tail>, T> +{ +private: + enum { tmp = TypeLocator<Tail, T>::value }; +public: + enum { value = tmp == -1 ? -1 : 1 + tmp }; +}; + + +template <class Head, class T> +struct TypeAppender; + /// TypeAppender appends T (type or a TypeList) to Head. + /// + /// Usage: + /// + /// typedef TypeListType<char>::HeadType Type1; + /// typedef TypeAppender<Type1, int>::HeadType Type2; + /// (Type2 is a TypeList of char,int) + /// + /// typedef TypeListType<float, double>::HeadType Type3; + /// typedef TypeAppender<Type2, Type3>::HeadType Type4; + /// (Type4 is a TypeList of char,int,float,double) + /// + + +template <> +struct TypeAppender<NullTypeList, NullTypeList> +{ + typedef NullTypeList HeadType; +}; + + +template <class T> +struct TypeAppender<NullTypeList, T> +{ + typedef TypeList<T, NullTypeList> HeadType; +}; + + +template <class Head, class Tail> +struct TypeAppender<NullTypeList, TypeList<Head, Tail> > +{ + typedef TypeList<Head, Tail> HeadType; +}; + + +template <class Head, class Tail, class T> +struct TypeAppender<TypeList<Head, Tail>, T> +{ + typedef TypeList<Head, typename TypeAppender<Tail, T>::HeadType> HeadType; +}; + + +template <class Head, class T> +struct TypeOneEraser; + /// TypeOneEraser erases the first occurence of the type T in Head. + /// Usage: + /// + /// typedef TypeListType<char, int, float>::HeadType Type3; + /// typedef TypeOneEraser<Type3, int>::HeadType Type2; + /// (Type2 is a TypeList of char,float) + /// + + +template <class T> +struct TypeOneEraser<NullTypeList, T> +{ + typedef NullTypeList HeadType; +}; + + +template <class T, class Tail> +struct TypeOneEraser<TypeList<T, Tail>, T> +{ + typedef Tail HeadType; +}; + + +template <class Head, class Tail, class T> +struct TypeOneEraser<TypeList<Head, Tail>, T> +{ + typedef TypeList <Head, typename TypeOneEraser<Tail, T>::HeadType> HeadType; +}; + + +template <class Head, class T> +struct TypeAllEraser; + /// TypeAllEraser erases all the occurences of the type T in Head. + /// Usage: + /// + /// typedef TypeListType<char, int, float, int>::HeadType Type4; + /// typedef TypeAllEraser<Type4, int>::HeadType Type2; + /// (Type2 is a TypeList of char,float) + /// + + +template <class T> +struct TypeAllEraser<NullTypeList, T> +{ + typedef NullTypeList HeadType; +}; + + +template <class T, class Tail> +struct TypeAllEraser<TypeList<T, Tail>, T> +{ + typedef typename TypeAllEraser<Tail, T>::HeadType HeadType; +}; + + +template <class Head, class Tail, class T> +struct TypeAllEraser<TypeList<Head, Tail>, T> +{ + typedef TypeList <Head, typename TypeAllEraser<Tail, T>::HeadType> HeadType; +}; + + +template <class Head> +struct TypeDuplicateEraser; + /// TypeDuplicateEraser erases all but the first occurence of the type T in Head. + /// Usage: + /// + /// typedef TypeListType<char, int, float, int>::HeadType Type4; + /// typedef TypeDuplicateEraser<Type4, int>::HeadType Type3; + /// (Type3 is a TypeList of char,int,float) + /// + + +template <> +struct TypeDuplicateEraser<NullTypeList> +{ + typedef NullTypeList HeadType; +}; + + +template <class Head, class Tail> +struct TypeDuplicateEraser<TypeList<Head, Tail> > +{ +private: + typedef typename TypeDuplicateEraser<Tail>::HeadType L1; + typedef typename TypeOneEraser<L1, Head>::HeadType L2; +public: + typedef TypeList<Head, L2> HeadType; +}; + + +template <class Head, class T, class R> +struct TypeOneReplacer; + /// TypeOneReplacer replaces the first occurence + /// of the type T in Head with type R. + /// Usage: + /// + /// typedef TypeListType<char, int, float, int>::HeadType Type4; + /// typedef TypeOneReplacer<Type4, int, double>::HeadType TypeR; + /// (TypeR is a TypeList of char,double,float,int) + /// + + +template <class T, class R> +struct TypeOneReplacer<NullTypeList, T, R> +{ + typedef NullTypeList HeadType; +}; + + +template <class T, class Tail, class R> +struct TypeOneReplacer<TypeList<T, Tail>, T, R> +{ + typedef TypeList<R, Tail> HeadType; +}; + + +template <class Head, class Tail, class T, class R> +struct TypeOneReplacer<TypeList<Head, Tail>, T, R> +{ + typedef TypeList<Head, typename TypeOneReplacer<Tail, T, R>::HeadType> HeadType; +}; + + +template <class Head, class T, class R> +struct TypeAllReplacer; + /// TypeAllReplacer replaces all the occurences + /// of the type T in Head with type R. + /// Usage: + /// + /// typedef TypeListType<char, int, float, int>::HeadType Type4; + /// typedef TypeAllReplacer<Type4, int, double>::HeadType TypeR; + /// (TypeR is a TypeList of char,double,float,double) + /// + + +template <class T, class R> +struct TypeAllReplacer<NullTypeList, T, R> +{ + typedef NullTypeList HeadType; +}; + + +template <class T, class Tail, class R> +struct TypeAllReplacer<TypeList<T, Tail>, T, R> +{ + typedef TypeList<R, typename TypeAllReplacer<Tail, T, R>::HeadType> HeadType; +}; + + +template <class Head, class Tail, class T, class R> +struct TypeAllReplacer<TypeList<Head, Tail>, T, R> +{ + typedef TypeList<Head, typename TypeAllReplacer<Tail, T, R>::HeadType> HeadType; +}; + + +} // namespace Poco + + +#endif // Foundation_TypeList_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Types.h b/contrib/libs/poco/Foundation/include/Poco/Types.h new file mode 100644 index 0000000000..f3d2ebc004 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Types.h @@ -0,0 +1,201 @@ +// +// Types.h +// +// Library: Foundation +// Package: Core +// Module: Types +// +// Definitions of fixed-size integer types for various platforms +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Types_INCLUDED +#define Foundation_Types_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +#if defined(_MSC_VER) + // + // Windows/Visual C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed __int64 Int64; + typedef unsigned __int64 UInt64; + #if defined(_WIN64) + #define POCO_PTR_IS_64_BIT 1 + typedef signed __int64 IntPtr; + typedef unsigned __int64 UIntPtr; + #else + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__GNUC__) || defined(__clang__) + // + // Unix/GCC/Clang + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + #if defined(_WIN64) + #define POCO_PTR_IS_64_BIT 1 + typedef signed long long IntPtr; + typedef unsigned long long UIntPtr; + typedef signed long long Int64; + typedef unsigned long long UInt64; + #else + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if defined(__LP64__) + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__DECCXX) + // + // Compaq C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed __int64 Int64; + typedef unsigned __int64 UInt64; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + #define POCO_HAVE_INT64 1 +#elif defined(__HP_aCC) + // + // HP Ansi C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if defined(__LP64__) + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__SUNPRO_CC) + // + // SUN Forte C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if defined(__sparcv9) + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__IBMCPP__) + // + // IBM XL C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if defined(__64BIT__) + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__sgi) + // + // MIPSpro C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if _MIPS_SZLONG == 64 + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(_DIAB_TOOL) + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + typedef signed long long Int64; + typedef unsigned long long UInt64; + #define POCO_HAVE_INT64 1 +#endif + + +} // namespace Poco + + +#endif // Foundation_Types_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/URI.h b/contrib/libs/poco/Foundation/include/Poco/URI.h new file mode 100644 index 0000000000..b6d41de93d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/URI.h @@ -0,0 +1,406 @@ +// +// URI.h +// +// Library: Foundation +// Package: URI +// Module: URI +// +// Definition of the URI class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_URI_INCLUDED +#define Foundation_URI_INCLUDED + + +#include "Poco/Foundation.h" +#include <vector> +#include <utility> + + +namespace Poco { + + +class Path; + + +class Foundation_API URI + /// A Uniform Resource Identifier, as specified in RFC 3986. + /// + /// The URI class provides methods for building URIs from their + /// parts, as well as for splitting URIs into their parts. + /// Furthermore, the class provides methods for resolving + /// relative URIs against base URIs. + /// + /// The class automatically performs a few normalizations on + /// all URIs and URI parts passed to it: + /// * scheme identifiers are converted to lower case + /// * percent-encoded characters are decoded (except for the query string) + /// * optionally, dot segments are removed from paths (see normalize()) + /// + /// Note that dealing with query strings requires some precautions, as, internally, + /// query strings are stored in percent-encoded form, while all other parts of the URI + /// are stored in decoded form. While parsing query strings from properly encoded URLs + /// generally works, explicitly setting query strings with setQuery() or extracting + /// query strings with getQuery() may lead to ambiguities. See the descriptions of + /// setQuery(), setRawQuery(), getQuery() and getRawQuery() for more information. +{ +public: + typedef std::vector<std::pair<std::string, std::string> > QueryParameters; + + URI(); + /// Creates an empty URI. + + explicit URI(const std::string& uri); + /// Parses an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + explicit URI(const char* uri); + /// Parses an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + URI(const std::string& scheme, const std::string& pathEtc); + /// Creates an URI from its parts. + + URI(const std::string& scheme, const std::string& authority, const std::string& pathEtc); + /// Creates an URI from its parts. + + URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query); + /// Creates an URI from its parts. + + URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query, const std::string& fragment); + /// Creates an URI from its parts. + + URI(const URI& uri); + /// Copy constructor. Creates an URI from another one. + + URI(const URI& baseURI, const std::string& relativeURI); + /// Creates an URI from a base URI and a relative URI, according to + /// the algorithm in section 5.2 of RFC 3986. + + explicit URI(const Path& path); + /// Creates a URI from a path. + /// + /// The path will be made absolute, and a file:// URI + /// will be built from it. + + ~URI(); + /// Destroys the URI. + + URI& operator = (const URI& uri); + /// Assignment operator. + + URI& operator = (const std::string& uri); + /// Parses and assigns an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + URI& operator = (const char* uri); + /// Parses and assigns an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + void swap(URI& uri); + /// Swaps the URI with another one. + + void clear(); + /// Clears all parts of the URI. + + std::string toString() const; + /// Returns a string representation of the URI. + /// + /// Characters in the path, query and fragment parts will be + /// percent-encoded as necessary. + + const std::string& getScheme() const; + /// Returns the scheme part of the URI. + + void setScheme(const std::string& scheme); + /// Sets the scheme part of the URI. The given scheme + /// is converted to lower-case. + /// + /// A list of registered URI schemes can be found + /// at <http://www.iana.org/assignments/uri-schemes>. + + const std::string& getUserInfo() const; + /// Returns the user-info part of the URI. + + void setUserInfo(const std::string& userInfo); + /// Sets the user-info part of the URI. + + const std::string& getHost() const; + /// Returns the host part of the URI. + + void setHost(const std::string& host); + /// Sets the host part of the URI. + + unsigned short getPort() const; + /// Returns the port number part of the URI. + /// + /// If no port number (0) has been specified, the + /// well-known port number (e.g., 80 for http) for + /// the given scheme is returned if it is known. + /// Otherwise, 0 is returned. + + void setPort(unsigned short port); + /// Sets the port number part of the URI. + + std::string getAuthority() const; + /// Returns the authority part (userInfo, host and port) + /// of the URI. + /// + /// If the port number is a well-known port + /// number for the given scheme (e.g., 80 for http), it + /// is not included in the authority. + + void setAuthority(const std::string& authority); + /// Parses the given authority part for the URI and sets + /// the user-info, host, port components accordingly. + + const std::string& getPath() const; + /// Returns the decoded path part of the URI. + + void setPath(const std::string& path); + /// Sets the path part of the URI. + + std::string getQuery() const; + /// Returns the decoded query part of the URI. + /// + /// Note that encoded ampersand characters ('&', "%26") + /// will be decoded, which could cause ambiguities if the query + /// string contains multiple parameters and a parameter name + /// or value contains an ampersand as well. + /// In such a case it's better to use getRawQuery() or + /// getQueryParameters(). + + void setQuery(const std::string& query); + /// Sets the query part of the URI. + /// + /// The query string will be percent-encoded. If the query + /// already contains percent-encoded characters, these + /// will be double-encoded, which is probably not what's + /// intended by the caller. Furthermore, ampersand ('&') + /// characters in the query will not be encoded. This could + /// lead to ambiguity issues if the query string contains multiple + /// name-value parameters separated by ampersand, and if any + /// name or value also contains an ampersand. In such a + /// case, it's better to use setRawQuery() with a properly + /// percent-encoded query string, or use addQueryParameter() + /// or setQueryParameters(), which take care of appropriate + /// percent encoding of parameter names and values. + + void addQueryParameter(const std::string& param, const std::string& val = ""); + /// Adds "param=val" to the query; "param" may not be empty. + /// If val is empty, only '=' is appended to the parameter. + /// + /// In addition to regular encoding, function also encodes '&' and '=', + /// if found in param or val. + + const std::string& getRawQuery() const; + /// Returns the query string in raw form, which usually + /// means percent encoded. + + void setRawQuery(const std::string& query); + /// Sets the query part of the URI. + /// + /// The given query string must be properly percent-encoded. + + QueryParameters getQueryParameters() const; + /// Returns the decoded query string parameters as a vector + /// of name-value pairs. + + void setQueryParameters(const QueryParameters& params); + /// Sets the query part of the URI from a vector + /// of query parameters. + /// + /// Calls addQueryParameter() for each parameter name and value. + + const std::string& getFragment() const; + /// Returns the fragment part of the URI. + + void setFragment(const std::string& fragment); + /// Sets the fragment part of the URI. + + void setPathEtc(const std::string& pathEtc); + /// Sets the path, query and fragment parts of the URI. + + std::string getPathEtc() const; + /// Returns the encoded path, query and fragment parts of the URI. + + std::string getPathAndQuery() const; + /// Returns the encoded path and query parts of the URI. + + void resolve(const std::string& relativeURI); + /// Resolves the given relative URI against the base URI. + /// See section 5.2 of RFC 3986 for the algorithm used. + + void resolve(const URI& relativeURI); + /// Resolves the given relative URI against the base URI. + /// See section 5.2 of RFC 3986 for the algorithm used. + + bool isRelative() const; + /// Returns true if the URI is a relative reference, false otherwise. + /// + /// A relative reference does not contain a scheme identifier. + /// Relative references are usually resolved against an absolute + /// base reference. + + bool empty() const; + /// Returns true if the URI is empty, false otherwise. + + bool operator == (const URI& uri) const; + /// Returns true if both URIs are identical, false otherwise. + /// + /// Two URIs are identical if their scheme, authority, + /// path, query and fragment part are identical. + + bool operator == (const std::string& uri) const; + /// Parses the given URI and returns true if both URIs are identical, + /// false otherwise. + + bool operator != (const URI& uri) const; + /// Returns true if both URIs are identical, false otherwise. + + bool operator != (const std::string& uri) const; + /// Parses the given URI and returns true if both URIs are identical, + /// false otherwise. + + void normalize(); + /// Normalizes the URI by removing all but leading . and .. segments from the path. + /// + /// If the first path segment in a relative path contains a colon (:), + /// such as in a Windows path containing a drive letter, a dot segment (./) + /// is prepended in accordance with section 3.3 of RFC 3986. + + void getPathSegments(std::vector<std::string>& segments); + /// Places the single path segments (delimited by slashes) into the + /// given vector. + + static void encode(const std::string& str, const std::string& reserved, std::string& encodedStr); + /// URI-encodes the given string by escaping reserved and non-ASCII + /// characters. The encoded string is appended to encodedStr. + + static void decode(const std::string& str, std::string& decodedStr, bool plusAsSpace = false); + /// URI-decodes the given string by replacing percent-encoded + /// characters with the actual character. The decoded string + /// is appended to decodedStr. + /// + /// When plusAsSpace is true, non-encoded plus signs in the query are decoded as spaces. + /// (http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1) + +protected: + bool equals(const URI& uri) const; + /// Returns true if both uri's are equivalent. + + bool isWellKnownPort() const; + /// Returns true if the URI's port number is a well-known one + /// (for example, 80, if the scheme is http). + + unsigned short getWellKnownPort() const; + /// Returns the well-known port number for the URI's scheme, + /// or 0 if the port number is not known. + + void parse(const std::string& uri); + /// Parses and assigns an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + void parseAuthority(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the user-info, host and port from the given data. + + void parseHostAndPort(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the host and port from the given data. + + void parsePath(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the path from the given data. + + void parsePathEtc(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the path, query and fragment from the given data. + + void parseQuery(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the query from the given data. + + void parseFragment(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the fragment from the given data. + + void mergePath(const std::string& path); + /// Appends a path to the URI's path. + + void removeDotSegments(bool removeLeading = true); + /// Removes all dot segments from the path. + + static void getPathSegments(const std::string& path, std::vector<std::string>& segments); + /// Places the single path segments (delimited by slashes) into the + /// given vector. + + void buildPath(const std::vector<std::string>& segments, bool leadingSlash, bool trailingSlash); + /// Builds the path from the given segments. + + static const std::string RESERVED_PATH; + static const std::string RESERVED_QUERY; + static const std::string RESERVED_QUERY_PARAM; + static const std::string RESERVED_FRAGMENT; + static const std::string ILLEGAL; + +private: + std::string _scheme; + std::string _userInfo; + std::string _host; + unsigned short _port; + std::string _path; + std::string _query; + std::string _fragment; +}; + + +// +// inlines +// +inline const std::string& URI::getScheme() const +{ + return _scheme; +} + + +inline const std::string& URI::getUserInfo() const +{ + return _userInfo; +} + + +inline const std::string& URI::getHost() const +{ + return _host; +} + + +inline const std::string& URI::getPath() const +{ + return _path; +} + + +inline const std::string& URI::getRawQuery() const +{ + return _query; +} + + +inline const std::string& URI::getFragment() const +{ + return _fragment; +} + + +inline void swap(URI& u1, URI& u2) +{ + u1.swap(u2); +} + + +} // namespace Poco + + +#endif // Foundation_URI_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/URIStreamFactory.h b/contrib/libs/poco/Foundation/include/Poco/URIStreamFactory.h new file mode 100644 index 0000000000..c5efa22bdd --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/URIStreamFactory.h @@ -0,0 +1,97 @@ +// +// URIStreamFactory.h +// +// Library: Foundation +// Package: URI +// Module: URIStreamFactory +// +// Definition of the URIStreamFactory class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_URIStreamFactory_INCLUDED +#define Foundation_URIStreamFactory_INCLUDED + + +#include "Poco/Foundation.h" +#include <istream> + + +namespace Poco { + + +class URI; + + +class Foundation_API URIStreamFactory + /// This class defines the interface that all + /// URI stream factories must implement. + /// + /// Subclasses must implement the open() method. +{ +public: + URIStreamFactory(); + /// Creates the URIStreamFactory. + + virtual std::istream* open(const URI& uri) = 0; + /// Tries to create and open an input stream for the + /// resource specified by the given URI. + /// + /// If the stream cannot be opened for whatever reason, + /// an appropriate IOException must be thrown. + /// + /// If opening the stream results in a redirect, a + /// URIRedirection exception should be thrown. + +protected: + virtual ~URIStreamFactory(); + /// Destroys the URIStreamFactory. + +private: + URIStreamFactory(const URIStreamFactory&); + URIStreamFactory& operator = (const URIStreamFactory&); + + friend class URIStreamOpener; +}; + + +class Foundation_API URIRedirection + /// An instance of URIRedirection is thrown by a URIStreamFactory::open() + /// if opening the original URI resulted in a redirection response + /// (such as a MOVED PERMANENTLY in HTTP). +{ +public: + URIRedirection(const std::string& uri); + URIRedirection(const URIRedirection& redir); + + URIRedirection& operator = (const URIRedirection& redir); + void swap(URIRedirection& redir); + + const std::string& uri() const; + /// Returns the new URI. + +private: + URIRedirection(); + + std::string _uri; +}; + + +// +// inlines +// +inline const std::string& URIRedirection::uri() const +{ + return _uri; +} + + +} // namespace Poco + + +#endif // Foundation_URIStreamFactory_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/URIStreamOpener.h b/contrib/libs/poco/Foundation/include/Poco/URIStreamOpener.h new file mode 100644 index 0000000000..85de22b1ab --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/URIStreamOpener.h @@ -0,0 +1,135 @@ +// +// URIStreamOpener.h +// +// Library: Foundation +// Package: URI +// Module: URIStreamOpener +// +// Definition of the URIStreamOpener class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_URIStreamOpener_INCLUDED +#define Foundation_URIStreamOpener_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include <istream> +#include <map> + + +namespace Poco { + + +class URI; +class URIStreamFactory; +class Path; + + +class Foundation_API URIStreamOpener + /// The URIStreamOpener class is used to create and open input streams + /// for resourced identified by Uniform Resource Identifiers. + /// + /// For every URI scheme used, a URIStreamFactory must be registered. + /// A FileStreamFactory is automatically registered for file URIs. +{ +public: + enum + { + MAX_REDIRECTS = 10 + }; + + URIStreamOpener(); + /// Creates the URIStreamOpener and registers a FileStreamFactory + /// for file URIs. + + ~URIStreamOpener(); + /// Destroys the URIStreamOpener and deletes all registered + /// URI stream factories. + + std::istream* open(const URI& uri) const; + /// Tries to create and open an input stream for the resource specified + /// by the given uniform resource identifier. + /// + /// If no URIStreamFactory has been registered for the URI's + /// scheme, a UnknownURIScheme exception is thrown. + /// If the stream cannot be opened for any reason, an + /// IOException is thrown. + /// + /// The given URI must be a valid one. This excludes file system paths. + /// + /// Whoever calls the method is responsible for deleting + /// the returned stream. + + std::istream* open(const std::string& pathOrURI) const; + /// Tries to create and open an input stream for the resource specified + /// by the given path or uniform resource identifier. + /// + /// If the stream cannot be opened for any reason, an + /// Exception is thrown. + /// + /// The method first tries to interpret the given pathOrURI as an URI. + /// If this fails, the pathOrURI is treated as local filesystem path. + /// If this also fails, an exception is thrown. + /// + /// Whoever calls the method is responsible for deleting + /// the returned stream. + + std::istream* open(const std::string& basePathOrURI, const std::string& pathOrURI) const; + /// Tries to create and open an input stream for the resource specified + /// by the given path or uniform resource identifier. + /// + /// pathOrURI is resolved against basePathOrURI (see URI::resolve() and + /// Path::resolve() for more information). + /// + /// If the stream cannot be opened for any reason, an + /// Exception is thrown. + /// + /// Whoever calls the method is responsible for deleting + /// the returned stream. + + void registerStreamFactory(const std::string& scheme, URIStreamFactory* pFactory); + /// Registers a URIStreamFactory for the given scheme. If another factory + /// has already been registered for the scheme, an ExistsException is thrown. + /// + /// The URIStreamOpener takes ownership of the factory and deletes it when it is + /// no longer needed (in other words, when the URIStreamOpener is deleted). + + void unregisterStreamFactory(const std::string& scheme); + /// Unregisters and deletes the URIStreamFactory for the given scheme. + /// + /// Throws a NotFoundException if no URIStreamFactory has been registered + /// for the given scheme. + + bool supportsScheme(const std::string& scheme); + /// Returns true iff a URIStreamFactory for the given scheme + /// has been registered. + + static URIStreamOpener& defaultOpener(); + /// Returns a reference to the default URIStreamOpener. + +protected: + std::istream* openFile(const Path& path) const; + std::istream* openURI(const std::string& scheme, const URI& uri) const; + +private: + URIStreamOpener(const URIStreamOpener&); + URIStreamOpener& operator = (const URIStreamOpener&); + + typedef std::map<std::string, URIStreamFactory*> FactoryMap; + + FactoryMap _map; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_URIStreamOpener_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UTF16Encoding.h b/contrib/libs/poco/Foundation/include/Poco/UTF16Encoding.h new file mode 100644 index 0000000000..0d38a71ddf --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UTF16Encoding.h @@ -0,0 +1,85 @@ +// +// UTF16Encoding.h +// +// Library: Foundation +// Package: Text +// Module: UTF16Encoding +// +// Definition of the UTF16Encoding class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UTF16Encoding_INCLUDED +#define Foundation_UTF16Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API UTF16Encoding: public TextEncoding + /// UTF-16 text encoding, as defined in RFC 2781. + /// + /// When converting from UTF-16 to Unicode, surrogates are + /// reported as they are - in other words, surrogate pairs + /// are not combined into one Unicode character. + /// When converting from Unicode to UTF-16, however, characters + /// outside the 16-bit range are converted into a low and + /// high surrogate. +{ +public: + enum ByteOrderType + { + BIG_ENDIAN_BYTE_ORDER, + LITTLE_ENDIAN_BYTE_ORDER, + NATIVE_BYTE_ORDER + }; + + UTF16Encoding(ByteOrderType byteOrder = NATIVE_BYTE_ORDER); + /// Creates and initializes the encoding for the given byte order. + + UTF16Encoding(int byteOrderMark); + /// Creates and initializes the encoding for the byte-order + /// indicated by the given byte-order mark, which is the Unicode + /// character 0xFEFF. + + ~UTF16Encoding(); + + ByteOrderType getByteOrder() const; + /// Returns the byte-order currently in use. + + void setByteOrder(ByteOrderType byteOrder); + /// Sets the byte order. + + void setByteOrder(int byteOrderMark); + /// Sets the byte order according to the given + /// byte order mark, which is the Unicode + /// character 0xFEFF. + + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + bool _flipBytes; + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_UTF16Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UTF32Encoding.h b/contrib/libs/poco/Foundation/include/Poco/UTF32Encoding.h new file mode 100644 index 0000000000..6f8af525a6 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UTF32Encoding.h @@ -0,0 +1,82 @@ +// +// UTF32Encoding.h +// +// Library: Foundation +// Package: Text +// Module: UTF32Encoding +// +// Definition of the UTF32Encoding class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UTF32Encoding_INCLUDED +#define Foundation_UTF32Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API UTF32Encoding: public TextEncoding + /// UTF-32 text encoding, as defined in RFC 2781. + /// + /// When converting from UTF-32 to Unicode, surrogates are + /// reported as they are - in other words, surrogate pairs + /// are not combined into one Unicode character. +{ +public: + enum ByteOrderType + { + BIG_ENDIAN_BYTE_ORDER, + LITTLE_ENDIAN_BYTE_ORDER, + NATIVE_BYTE_ORDER + }; + + UTF32Encoding(ByteOrderType byteOrder = NATIVE_BYTE_ORDER); + /// Creates and initializes the encoding for the given byte order. + + UTF32Encoding(int byteOrderMark); + /// Creates and initializes the encoding for the byte-order + /// indicated by the given byte-order mark, which is the Unicode + /// character 0xFEFF. + + ~UTF32Encoding(); + + ByteOrderType getByteOrder() const; + /// Returns the byte-order currently in use. + + void setByteOrder(ByteOrderType byteOrder); + /// Sets the byte order. + + void setByteOrder(int byteOrderMark); + /// Sets the byte order according to the given + /// byte order mark, which is the Unicode + /// character 0xFEFF. + + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + bool _flipBytes; + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_UTF32Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UTF8Encoding.h b/contrib/libs/poco/Foundation/include/Poco/UTF8Encoding.h new file mode 100644 index 0000000000..66e29d2d00 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UTF8Encoding.h @@ -0,0 +1,61 @@ +// +// UTF8Encoding.h +// +// Library: Foundation +// Package: Text +// Module: UTF8Encoding +// +// Definition of the UTF8Encoding class. +// +// Copyright (c) 2004-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UTF8Encoding_INCLUDED +#define Foundation_UTF8Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API UTF8Encoding: public TextEncoding + /// UTF-8 text encoding, as defined in RFC 2279. +{ +public: + UTF8Encoding(); + ~UTF8Encoding(); + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + + static bool isLegal(const unsigned char *bytes, int length); + /// Utility routine to tell whether a sequence of bytes is legal UTF-8. + /// This must be called with the length pre-determined by the first byte. + /// The sequence is illegal right away if there aren't enough bytes + /// available. If presented with a length > 4, this function returns false. + /// The Unicode definition of UTF-8 goes up to 4-byte sequences. + /// + /// Adapted from ftp://ftp.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c + /// Copyright 2001-2004 Unicode, Inc. + +private: + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_UTF8Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UTF8String.h b/contrib/libs/poco/Foundation/include/Poco/UTF8String.h new file mode 100644 index 0000000000..73898c65c1 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UTF8String.h @@ -0,0 +1,83 @@ +// +// UTF8String.h +// +// Library: Foundation +// Package: Text +// Module: UTF8String +// +// Definition of the UTF8 string functions. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UTF8String_INCLUDED +#define Foundation_UTF8String_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +struct Foundation_API UTF8 + /// This class provides static methods that are UTF-8 capable variants + /// of the same functions in Poco/String.h. + /// + /// The various variants of icompare() provide case insensitive comparison + /// for UTF-8 encoded strings. + /// + /// toUpper(), toUpperInPlace(), toLower() and toLowerInPlace() provide + /// Unicode-based character case transformation for UTF-8 encoded strings. + /// + /// removeBOM() removes the UTF-8 Byte Order Mark sequence (0xEF, 0xBB, 0xBF) + /// from the beginning of the given string, if it's there. +{ + static int icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, std::string::const_iterator it2, std::string::const_iterator end2); + static int icompare(const std::string& str1, const std::string& str2); + static int icompare(const std::string& str1, std::string::size_type n1, const std::string& str2, std::string::size_type n2); + static int icompare(const std::string& str1, std::string::size_type n, const std::string& str2); + static int icompare(const std::string& str1, std::string::size_type pos, std::string::size_type n, const std::string& str2); + static int icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n1, const std::string& str2, std::string::size_type pos2, std::string::size_type n2); + static int icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n, const std::string& str2, std::string::size_type pos2); + static int icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, const std::string::value_type* ptr); + static int icompare(const std::string& str, std::string::size_type pos, const std::string::value_type* ptr); + static int icompare(const std::string& str, const std::string::value_type* ptr); + + static std::string toUpper(const std::string& str); + static std::string& toUpperInPlace(std::string& str); + static std::string toLower(const std::string& str); + static std::string& toLowerInPlace(std::string& str); + + static void removeBOM(std::string& str); + /// Remove the UTF-8 Byte Order Mark sequence (0xEF, 0xBB, 0xBF) + /// from the beginning of the string, if it's there. + + static std::string escape(const std::string& s, bool strictJSON = false); + /// Escapes a string. Special characters like tab, backslash, ... are + /// escaped. Unicode characters are escaped to \uxxxx. + /// If strictJSON is true, \a and \v will be escaped to \\u0007 and \\u000B + /// instead of \\a and \\v for strict JSON conformance. + + static std::string escape(const std::string::const_iterator& begin, const std::string::const_iterator& end, bool strictJSON = false); + /// Escapes a string. Special characters like tab, backslash, ... are + /// escaped. Unicode characters are escaped to \uxxxx. + /// If strictJSON is true, \a and \v will be escaped to \\u0007 and \\u000B + /// instead of \\a and \\v for strict JSON conformance. + + static std::string unescape(const std::string& s); + /// Creates an UTF8 string from a string that contains escaped characters. + + static std::string unescape(const std::string::const_iterator& begin, const std::string::const_iterator& end); + /// Creates an UTF8 string from a string that contains escaped characters. +}; + + +} // namespace Poco + + +#endif // Foundation_UTF8String_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UTFString.h b/contrib/libs/poco/Foundation/include/Poco/UTFString.h new file mode 100644 index 0000000000..7364583e79 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UTFString.h @@ -0,0 +1,305 @@ +// +// UTFString.h +// +// Library: Foundation +// Package: Text +// Module: UTFString +// +// Definitions of strings for UTF encodings. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UTFString_INCLUDED +#define Foundation_UTFString_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Types.h" +#include <string> + + +namespace Poco { + + +struct UTF16CharTraits +{ + typedef std::fpos<std::mbstate_t> u16streampos; + typedef UInt16 char_type; + typedef int int_type; + typedef std::streamoff off_type; + typedef u16streampos pos_type; + typedef std::mbstate_t state_type; + + static void assign(char_type& c1, const char_type& c2) + { + c1 = c2; + } + + static bool eq(char_type c1, char_type c2) + { + return c1 == c2; + } + + static bool lt(char_type c1, char_type c2) + { + return c1 < c2; + } + + static int compare(const char_type* s1, const char_type* s2, std::size_t n) + { + for (; n; --n, ++s1, ++s2) + { + if (lt(*s1, *s2)) + return -1; + if (lt(*s2, *s1)) + return 1; + } + return 0; + } + + static std::size_t length(const char_type* s) + { + std::size_t len = 0; + for (; !eq(*s, char_type(0)); ++s) + ++len; + return len; + } + + static const char_type* find(const char_type* s, std::size_t n, const char_type& a) + { + for (; n; --n) + { + if (eq(*s, a)) + return s; + ++s; + } + return 0; + } + + static char_type* move(char_type* s1, const char_type* s2, std::size_t n) + { + char_type* r = s1; + if (s1 < s2) + { + for (; n; --n, ++s1, ++s2) + assign(*s1, *s2); + } + else if (s2 < s1) + { + s1 += n; + s2 += n; + for (; n; --n) + assign(*--s1, *--s2); + } + return r; + } + + static char_type* copy(char_type* s1, const char_type* s2, std::size_t n) + { + poco_assert(s2 < s1 || s2 >= s1 + n); + char_type* r = s1; + for (; n; --n, ++s1, ++s2) + assign(*s1, *s2); + return r; + } + + static char_type* assign(char_type* s, std::size_t n, char_type a) + { + char_type* r = s; + for (; n; --n, ++s) + assign(*s, a); + return r; + } + + static int_type not_eof(int_type c) + { + return eq_int_type(c, eof()) ? ~eof() : c; + } + + static char_type to_char_type(int_type c) + { + return char_type(c); + } + + static int_type to_int_type(char_type c) + { + return int_type(c); + } + + static bool eq_int_type(int_type c1, int_type c2) + { + return c1 == c2; + } + + static int_type eof() + { + return int_type(0xDFFF); + } +}; + + +struct UTF32CharTraits +{ + typedef std::fpos<std::mbstate_t> u32streampos; + typedef UInt32 char_type; + typedef int int_type; + typedef std::streamoff off_type; + typedef u32streampos pos_type; + typedef std::mbstate_t state_type; + + static void assign(char_type& c1, const char_type& c2) + { + c1 = c2; + } + + static bool eq(char_type c1, char_type c2) + { + return c1 == c2; + } + + static bool lt(char_type c1, char_type c2) + { + return c1 < c2; + } + + static int compare(const char_type* s1, const char_type* s2, std::size_t n) + { + for (; n; --n, ++s1, ++s2) + { + if (lt(*s1, *s2)) + return -1; + if (lt(*s2, *s1)) + return 1; + } + return 0; + } + + static std::size_t length(const char_type* s) + { + std::size_t len = 0; + for (; !eq(*s, char_type(0)); ++s) + ++len; + return len; + } + + static const char_type* find(const char_type* s, std::size_t n, const char_type& a) + { + for (; n; --n) + { + if (eq(*s, a)) + return s; + ++s; + } + return 0; + } + + static char_type* move(char_type* s1, const char_type* s2, std::size_t n) + { + char_type* r = s1; + if (s1 < s2) + { + for (; n; --n, ++s1, ++s2) + assign(*s1, *s2); + } + else if (s2 < s1) + { + s1 += n; + s2 += n; + for (; n; --n) + assign(*--s1, *--s2); + } + return r; + } + + static char_type* copy(char_type* s1, const char_type* s2, std::size_t n) + { + poco_assert(s2 < s1 || s2 >= s1 + n); + char_type* r = s1; + for (; n; --n, ++s1, ++s2) + assign(*s1, *s2); + return r; + } + + static char_type* assign(char_type* s, std::size_t n, char_type a) + { + char_type* r = s; + for (; n; --n, ++s) + assign(*s, a); + return r; + } + + static int_type not_eof(int_type c) + { + return eq_int_type(c, eof()) ? ~eof() : c; + } + + static char_type to_char_type(int_type c) + { + return char_type(c); + } + + static int_type to_int_type(char_type c) + { + return int_type(c); + } + + static bool eq_int_type(int_type c1, int_type c2) + { + return c1 == c2; + } + + static int_type eof() + { + return int_type(0xDFFF); + } +}; + + +//#if defined(POCO_ENABLE_CPP11) //TODO + // typedef char16_t UTF16Char; + // typedef std::u16string UTF16String; + // typedef char32_t UTF32Char; + // typedef std::u32string UTF32String; +//#else + #ifdef POCO_NO_WSTRING + typedef Poco::UInt16 UTF16Char; + typedef std::basic_string<UTF16Char, UTF16CharTraits> UTF16String; + typedef UInt32 UTF32Char; + typedef std::basic_string<UTF32Char, UTF32CharTraits> UTF32String; + #else // POCO_NO_WSTRING + #if defined(POCO_OS_FAMILY_WINDOWS) + typedef wchar_t UTF16Char; + typedef std::wstring UTF16String; + typedef UInt32 UTF32Char; + typedef std::basic_string<UTF32Char, UTF32CharTraits> UTF32String; + #elif defined(__SIZEOF_WCHAR_T__) //gcc + #if (__SIZEOF_WCHAR_T__ == 2) + typedef wchar_t UTF16Char; + typedef std::wstring UTF16String; + typedef UInt32 UTF32Char; + typedef std::basic_string<UTF32Char, UTF32CharTraits> UTF32String; + #elif (__SIZEOF_WCHAR_T__ == 4) + typedef Poco::UInt16 UTF16Char; + typedef std::basic_string<UTF16Char, UTF16CharTraits> UTF16String; + typedef wchar_t UTF32Char; + typedef std::wstring UTF32String; + #endif + #else // default to 32-bit wchar_t + typedef Poco::UInt16 UTF16Char; + typedef std::basic_string<UTF16Char, UTF16CharTraits> UTF16String; + typedef wchar_t UTF32Char; + typedef std::wstring UTF32String; + #endif //POCO_OS_FAMILY_WINDOWS + #endif //POCO_NO_WSTRING +//#endif // POCO_ENABLE_CPP11 + + +} // namespace Poco + + +#endif // Foundation_UTFString_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UUID.h b/contrib/libs/poco/Foundation/include/Poco/UUID.h new file mode 100644 index 0000000000..2708a0003a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UUID.h @@ -0,0 +1,219 @@ +// +// UUID.h +// +// Library: Foundation +// Package: UUID +// Module: UUID +// +// Definition of the UUID class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UUID_INCLUDED +#define Foundation_UUID_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API UUID + /// A UUID is an identifier that is unique across both space and time, + /// with respect to the space of all UUIDs. Since a UUID is a fixed + /// size and contains a time field, it is possible for values to + /// rollover (around A.D. 3400, depending on the specific algorithm + /// used). A UUID can be used for multiple purposes, from tagging + /// objects with an extremely short lifetime, to reliably identifying + /// very persistent objects across a network. + /// + /// This class implements a Universal Unique Identifier, + /// as specified in Appendix A of the DCE 1.1 Remote Procedure + /// Call Specification (http://www.opengroup.org/onlinepubs/9629399/), + /// RFC 2518 (WebDAV), section 6.4.1 and the UUIDs and GUIDs internet + /// draft by Leach/Salz from February, 1998 + /// (http://www.ics.uci.edu/~ejw/authoring/uuid-guid/draft-leach-uuids-guids-01.txt) + /// and also http://tools.ietf.org/html/draft-mealling-uuid-urn-05 +{ +public: + enum Version + { + UUID_TIME_BASED = 0x01, + UUID_DCE_UID = 0x02, + UUID_NAME_BASED = 0x03, + UUID_RANDOM = 0x04, + UUID_NAME_BASED_SHA1 = 0x05 + + }; + + UUID(); + /// Creates a nil (all zero) UUID. + + UUID(const UUID& uuid); + /// Copy constructor. + + explicit UUID(const std::string& uuid); + /// Parses the UUID from a string. + + explicit UUID(const char* uuid); + /// Parses the UUID from a string. + + ~UUID(); + /// Destroys the UUID. + + UUID& operator = (const UUID& uuid); + /// Assignment operator. + + void swap(UUID& uuid); + /// Swaps the UUID with another one. + + void parse(const std::string& uuid); + /// Parses the UUID from its string representation. + + bool tryParse(const std::string& uuid); + /// Tries to interpret the given string as an UUID. + /// If the UUID is syntactically valid, assigns the + /// members and returns true. Otherwise leaves the + /// object unchanged and returns false. + + std::string toString() const; + /// Returns a string representation of the UUID consisting + /// of groups of hexadecimal digits separated by hyphens. + + void copyFrom(const char* buffer); + /// Copies the UUID (16 bytes) from a buffer or byte array. + /// The UUID fields are expected to be + /// stored in network byte order. + /// The buffer need not be aligned. + + void copyTo(char* buffer) const; + /// Copies the UUID to the buffer. The fields + /// are in network byte order. + /// The buffer need not be aligned. + /// There must have room for at least 16 bytes. + + Version version() const; + /// Returns the version of the UUID. + + int variant() const; + /// Returns the variant number of the UUID: + /// - 0 reserved for NCS backward compatibility + /// - 2 the Leach-Salz variant (used by this class) + /// - 6 reserved, Microsoft Corporation backward compatibility + /// - 7 reserved for future definition + + bool operator == (const UUID& uuid) const; + bool operator != (const UUID& uuid) const; + bool operator < (const UUID& uuid) const; + bool operator <= (const UUID& uuid) const; + bool operator > (const UUID& uuid) const; + bool operator >= (const UUID& uuid) const; + + bool isNull() const; + /// Returns true iff the UUID is nil (in other words, + /// consists of all zeros). + + static const UUID& null(); + /// Returns a null/nil UUID. + + static const UUID& dns(); + /// Returns the namespace identifier for the DNS namespace. + + static const UUID& uri(); + /// Returns the namespace identifier for the URI (former URL) namespace. + + static const UUID& oid(); + /// Returns the namespace identifier for the OID namespace. + + static const UUID& x500(); + /// Returns the namespace identifier for the X500 namespace. + +protected: + UUID(UInt32 timeLow, UInt32 timeMid, UInt32 timeHiAndVersion, UInt16 clockSeq, UInt8 node[]); + UUID(const char* bytes, Version version); + int compare(const UUID& uuid) const; + static void appendHex(std::string& str, UInt8 n); + static void appendHex(std::string& str, UInt16 n); + static void appendHex(std::string& str, UInt32 n); + static Int16 nibble(char hex); + void fromNetwork(); + void toNetwork(); + +private: + UInt32 _timeLow; + UInt16 _timeMid; + UInt16 _timeHiAndVersion; + UInt16 _clockSeq; + UInt8 _node[6]; + + friend class UUIDGenerator; +}; + + +// +// inlines +// +inline bool UUID::operator == (const UUID& uuid) const +{ + return compare(uuid) == 0; +} + + +inline bool UUID::operator != (const UUID& uuid) const +{ + return compare(uuid) != 0; +} + + +inline bool UUID::operator < (const UUID& uuid) const +{ + return compare(uuid) < 0; +} + + +inline bool UUID::operator <= (const UUID& uuid) const +{ + return compare(uuid) <= 0; +} + + +inline bool UUID::operator > (const UUID& uuid) const +{ + return compare(uuid) > 0; +} + + +inline bool UUID::operator >= (const UUID& uuid) const +{ + return compare(uuid) >= 0; +} + + +inline UUID::Version UUID::version() const +{ + return Version(_timeHiAndVersion >> 12); +} + + +inline bool UUID::isNull() const +{ + return compare(null()) == 0; +} + + +inline void swap(UUID& u1, UUID& u2) +{ + u1.swap(u2); +} + + +} // namespace Poco + + +#endif // Foundation_UUID_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UUIDGenerator.h b/contrib/libs/poco/Foundation/include/Poco/UUIDGenerator.h new file mode 100644 index 0000000000..517417de93 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UUIDGenerator.h @@ -0,0 +1,104 @@ +// +// UUIDGenerator.h +// +// Library: Foundation +// Package: UUID +// Module: UUID +// +// Definition of the UUIDGenerator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UUIDGenerator_INCLUDED +#define Foundation_UUIDGenerator_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UUID.h" +#include "Poco/Mutex.h" +#include "Poco/Random.h" +#include "Poco/Timestamp.h" +#include "Poco/Environment.h" + + +namespace Poco { + + +class DigestEngine; + + +class Foundation_API UUIDGenerator + /// This class implements a generator for Universal Unique Identifiers, + /// as specified in Appendix A of the DCE 1.1 Remote Procedure + /// Call Specification (http://www.opengroup.org/onlinepubs/9629399/), + /// RFC 2518 (WebDAV), section 6.4.1 and the UUIDs and GUIDs internet + /// draft by Leach/Salz from February, 1998 + /// (http://ftp.ics.uci.edu/pub/ietf/webdav/uuid-guid/draft-leach-uuids-guids-01.txt) +{ +public: + UUIDGenerator(); + /// Creates the UUIDGenerator. + + ~UUIDGenerator(); + /// Destroys the UUIDGenerator. + + UUID create(); + /// Creates a new time-based UUID, using the MAC address of + /// one of the system's ethernet adapters. + /// + /// Throws a SystemException if no MAC address can be + /// obtained. + + UUID createFromName(const UUID& nsid, const std::string& name); + /// Creates a name-based UUID. + + UUID createFromName(const UUID& nsid, const std::string& name, DigestEngine& de); + /// Creates a name-based UUID, using the given digest engine. + /// + /// Note: in order to create a standard-compliant UUID, the given DigestEngine + /// must be either an instance of MD5Engine or SHA1Engine. The version field of + /// the UUID will be set accordingly. + + UUID createFromName(const UUID& nsid, const std::string& name, DigestEngine& de, UUID::Version version); + /// Creates a name-based UUID, using the given digest engine and version. + + UUID createRandom(); + /// Creates a random UUID. + + UUID createOne(); + /// Tries to create and return a time-based UUID (see create()), and, + /// if that does not work due to the unavailability of a MAC address, + /// creates and returns a random UUID (see createRandom()). + /// + /// The UUID::version() method can be used to determine the actual kind of + /// the UUID generated. + + static UUIDGenerator& defaultGenerator(); + /// Returns a reference to the default UUIDGenerator. + +protected: + Timestamp::UtcTimeVal timeStamp(); + void getNode(); + +private: + FastMutex _mutex; + Random _random; + Timestamp _lastTime; + int _ticks; + Environment::NodeId _node; + bool _haveNode; + + UUIDGenerator(const UUIDGenerator&); + UUIDGenerator& operator = (const UUIDGenerator&); +}; + + +} // namespace Poco + + +#endif // Foundation_UUIDGenerator_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UnWindows.h b/contrib/libs/poco/Foundation/include/Poco/UnWindows.h new file mode 100644 index 0000000000..a54b4a94c5 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UnWindows.h @@ -0,0 +1,142 @@ +// +// UnWindows.h +// +// Library: Foundation +// Package: Core +// Module: UnWindows +// +// A wrapper around the <windows.h> header file that #undef's some +// of the macros for function names defined by <windows.h> that +// are a frequent source of conflicts (e.g., GetUserName). +// +// Remember, that most of the WIN32 API functions come in two variants, +// an Unicode variant (e.g., GetUserNameA) and an ASCII variant (GetUserNameW). +// There is also a macro (GetUserName) that's either defined to be the Unicode +// name or the ASCII name, depending on whether the UNICODE macro is #define'd +// or not. POCO always calls the Unicode or ASCII functions directly (depending +// on whether POCO_WIN32_UTF8 is #define'd or not), so the macros are not ignored. +// +// These macro definitions are a frequent case of problems and naming conflicts, +// especially for C++ programmers. Say, you define a class with a member function named +// GetUserName. Depending on whether "Poco/UnWindows.h" has been included by a particular +// translation unit or not, this might be changed to GetUserNameA/GetUserNameW, or not. +// While, due to naming conventions used, this is less of a problem in POCO, some +// of the users of POCO might use a different naming convention where this can become +// a problem. +// +// To disable the #undef's, compile POCO with the POCO_NO_UNWINDOWS macro #define'd. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UnWindows_INCLUDED +#define Foundation_UnWindows_INCLUDED + + +// Reduce bloat +#if defined(_WIN32) + #if !defined(WIN32_LEAN_AND_MEAN) && !defined(POCO_BLOATED_WIN32) + #define WIN32_LEAN_AND_MEAN + #endif +#endif + + +// Microsoft Visual C++ includes copies of the Windows header files +// that were current at the time Visual C++ was released. +// The Windows header files use macros to indicate which versions +// of Windows support many programming elements. Therefore, you must +// define these macros to use new functionality introduced in each +// major operating system release. (Individual header files may use +// different macros; therefore, if compilation problems occur, check +// the header file that contains the definition for conditional +// definitions.) For more information, see SdkDdkVer.h. + + +#if !defined(_WIN32_WCE) +#if defined(_WIN32_WINNT) + #if (_WIN32_WINNT < 0x0502) + #error Unsupported Windows version. + #endif +#elif defined(NTDDI_VERSION) + #if (NTDDI_VERSION < 0x05020000) + #error Unsupported Windows version. + #endif +#elif !defined(_WIN32_WINNT) + // Define minimum supported version. + // This can be changed, if needed. + // If allowed (see POCO_MIN_WINDOWS_OS_SUPPORT + // below), Platform_WIN32.h will do its + // best to determine the appropriate values + // and may redefine these. See Platform_WIN32.h + // for details. + #define _WIN32_WINNT 0x0502 + #define NTDDI_VERSION 0x05020000 +#endif +#endif + + +// To prevent Platform_WIN32.h to modify version defines, +// uncomment this, otherwise versions will be automatically +// discovered in Platform_WIN32.h. +// #define POCO_FORCE_MIN_WINDOWS_OS_SUPPORT + + +#include <windows.h> + + +#if !defined(POCO_NO_UNWINDOWS) +// A list of annoying macros to #undef. +// Extend as required. +#undef GetBinaryType +#undef GetShortPathName +#undef GetLongPathName +#undef GetEnvironmentStrings +#undef SetEnvironmentStrings +#undef FreeEnvironmentStrings +#undef FormatMessage +#undef EncryptFile +#undef DecryptFile +#undef CreateMutex +#undef OpenMutex +#undef CreateEvent +#undef OpenEvent +#undef CreateSemaphore +#undef OpenSemaphore +#undef LoadLibrary +#undef GetModuleFileName +#undef CreateProcess +#undef GetCommandLine +#undef GetEnvironmentVariable +#undef SetEnvironmentVariable +#undef ExpandEnvironmentStrings +#undef OutputDebugString +#undef FindResource +#undef UpdateResource +#undef FindAtom +#undef AddAtom +#undef GetSystemDirectory +#undef GetTempPath +#undef GetTempFileName +#undef SetCurrentDirectory +#undef GetCurrentDirectory +#undef CreateDirectory +#undef RemoveDirectory +#undef CreateFile +#undef DeleteFile +#undef SearchPath +#undef CopyFile +#undef MoveFile +#undef ReplaceFile +#undef GetComputerName +#undef SetComputerName +#undef GetUserName +#undef LogonUser +#undef GetVersion +#undef GetObject +#endif // POCO_NO_UNWINDOWS + +#endif // Foundation_UnWindows_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UnbufferedStreamBuf.h b/contrib/libs/poco/Foundation/include/Poco/UnbufferedStreamBuf.h new file mode 100644 index 0000000000..ed56cb83ec --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UnbufferedStreamBuf.h @@ -0,0 +1,179 @@ +// +// UnufferedStreamBuf.h +// +// Library: Foundation +// Package: Streams +// Module: StreamBuf +// +// Definition of template BasicUnbufferedStreamBuf and class UnbufferedStreamBuf. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UnbufferedStreamBuf_INCLUDED +#define Foundation_UnbufferedStreamBuf_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/StreamUtil.h" +#include <streambuf> +#include <iosfwd> +#include <ios> + + +namespace Poco { + + +template <typename ch, typename tr> +class BasicUnbufferedStreamBuf: public std::basic_streambuf<ch, tr> + /// This is an implementation of an unbuffered streambuf + /// that greatly simplifies the implementation of + /// custom streambufs of various kinds. + /// Derived classes only have to override the methods + /// readFromDevice() or writeToDevice(). +{ +protected: + typedef std::basic_streambuf<ch, tr> Base; + typedef std::basic_ios<ch, tr> IOS; + typedef ch char_type; + typedef tr char_traits; + typedef typename Base::int_type int_type; + typedef typename Base::pos_type pos_type; + typedef typename Base::off_type off_type; + typedef typename IOS::openmode openmode; + +public: + BasicUnbufferedStreamBuf(): + _pb(char_traits::eof()), + _ispb(false) + { + this->setg(0, 0, 0); + this->setp(0, 0); + } + + ~BasicUnbufferedStreamBuf() + { + } + + virtual int_type overflow(int_type c) + { + if (c != char_traits::eof()) + return writeToDevice(char_traits::to_char_type(c)); + else + return c; + } + + virtual int_type underflow() + { + if (_ispb) + { + return _pb; + } + else + { + int_type c = readFromDevice(); + if (c != char_traits::eof()) + { + _ispb = true; + _pb = c; + } + return c; + } + } + + virtual int_type uflow() + { + if (_ispb) + { + _ispb = false; + return _pb; + } + else + { + int_type c = readFromDevice(); + if (c != char_traits::eof()) + { + _pb = c; + } + return c; + } + } + + virtual int_type pbackfail(int_type c) + { + if (_ispb) + { + return char_traits::eof(); + } + else + { + _ispb = true; + _pb = c; + return c; + } + } + + virtual std::streamsize xsgetn(char_type* p, std::streamsize count) + /// Some platforms (for example, Compaq C++) have buggy implementations of + /// xsgetn that handle null buffers incorrectly. + /// Anyway, it does not hurt to provide an optimized implementation + /// of xsgetn for this streambuf implementation. + { + std::streamsize copied = 0; + while (count > 0) + { + int_type c = uflow(); + if (c == char_traits::eof()) break; + *p++ = char_traits::to_char_type(c); + ++copied; + --count; + } + return copied; + } + +protected: + static int_type charToInt(char_type c) + { + return char_traits::to_int_type(c); + } + +private: + virtual int_type readFromDevice() + { + return char_traits::eof(); + } + + virtual int_type writeToDevice(char_type) + { + return char_traits::eof(); + } + + int_type _pb; + bool _ispb; + + BasicUnbufferedStreamBuf(const BasicUnbufferedStreamBuf&); + BasicUnbufferedStreamBuf& operator = (const BasicUnbufferedStreamBuf&); +}; + + +// +// We provide an instantiation for char. +// +// Visual C++ needs a workaround - explicitly importing the template +// instantiation - to avoid duplicate symbols due to multiple +// instantiations in different libraries. +// +#if defined(_MSC_VER) && defined(POCO_DLL) && !defined(Foundation_EXPORTS) +template class Foundation_API BasicUnbufferedStreamBuf<char, std::char_traits<char> >; +#endif +typedef BasicUnbufferedStreamBuf<char, std::char_traits<char> > UnbufferedStreamBuf; + + +} // namespace Poco + + +#endif // Foundation_UnbufferedStreamBuf_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Unicode.h b/contrib/libs/poco/Foundation/include/Poco/Unicode.h new file mode 100644 index 0000000000..b6d027685a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Unicode.h @@ -0,0 +1,327 @@ +// +// Unicode.h +// +// Library: Foundation +// Package: Text +// Module: Unicode +// +// Definition of the Unicode class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Unicode_INCLUDED +#define Foundation_Unicode_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Unicode + /// This class contains enumerations and static + /// utility functions for dealing with Unicode characters + /// and their properties. + /// + /// For more information on Unicode, see <http://www.unicode.org>. + /// + /// The implementation is based on the Unicode support + /// functions in PCRE. +{ +public: + // Implementation note: the following definitions must be kept + // in sync with those from ucp.h (PCRE). + enum CharacterCategory + /// Unicode character categories. + { + UCP_OTHER, + UCP_LETTER, + UCP_MARK, + UCP_NUMBER, + UCP_PUNCTUATION, + UCP_SYMBOL, + UCP_SEPARATOR + }; + + enum CharacterType + /// Unicode character types. + { + UCP_CONTROL, + UCP_FORMAT, + UCP_UNASSIGNED, + UCP_PRIVATE_USE, + UCP_SURROGATE, + UCP_LOWER_CASE_LETTER, + UCP_MODIFIER_LETTER, + UCP_OTHER_LETTER, + UCP_TITLE_CASE_LETTER, + UCP_UPPER_CASE_LETTER, + UCP_SPACING_MARK, + UCP_ENCLOSING_MARK, + UCP_NON_SPACING_MARK, + UCP_DECIMAL_NUMBER, + UCP_LETTER_NUMBER, + UCP_OTHER_NUMBER, + UCP_CONNECTOR_PUNCTUATION, + UCP_DASH_PUNCTUATION, + UCP_CLOSE_PUNCTUATION, + UCP_FINAL_PUNCTUATION, + UCP_INITIAL_PUNCTUATION, + UCP_OTHER_PUNCTUATION, + UCP_OPEN_PUNCTUATION, + UCP_CURRENCY_SYMBOL, + UCP_MODIFIER_SYMBOL, + UCP_MATHEMATICAL_SYMBOL, + UCP_OTHER_SYMBOL, + UCP_LINE_SEPARATOR, + UCP_PARAGRAPH_SEPARATOR, + UCP_SPACE_SEPARATOR + }; + + enum Script + /// Unicode 7.0 script identifiers. + { + UCP_ARABIC, + UCP_ARMENIAN, + UCP_BENGALI, + UCP_BOPOMOFO, + UCP_BRAILLE, + UCP_BUGINESE, + UCP_BUHID, + UCP_CANADIAN_ABORIGINAL, + UCP_CHEROKEE, + UCP_COMMON, + UCP_COPTIC, + UCP_CYPRIOT, + UCP_CYRILLIC, + UCP_DESERET, + UCP_DEVANAGARI, + UCP_ETHIOPIC, + UCP_GEORGIAN, + UCP_GLAGOLITIC, + UCP_GOTHIC, + UCP_GREEK, + UCP_GUJARATI, + UCP_GURMUKHI, + UCP_HAN, + UCP_HANGUL, + UCP_HANUNOO, + UCP_HEBREW, + UCP_HIRAGANA, + UCP_INHERITED, + UCP_KANNADA, + UCP_KATAKANA, + UCP_KHAROSHTHI, + UCP_KHMER, + UCP_LAO, + UCP_LATIN, + UCP_LIMBU, + UCP_LINEAR_B, + UCP_MALAYALAM, + UCP_MONGOLIAN, + UCP_MYANMAR, + UCP_NEW_TAI_LUE, + UCP_OGHAM, + UCP_OLD_ITALIC, + UCP_OLD_PERSIAN, + UCP_ORIYA, + UCP_OSMANYA, + UCP_RUNIC, + UCP_SHAVIAN, + UCP_SINHALA, + UCP_SYLOTI_NAGRI, + UCP_SYRIAC, + UCP_TAGALOG, + UCP_TAGBANWA, + UCP_TAI_LE, + UCP_TAMIL, + UCP_TELUGU, + UCP_THAANA, + UCP_THAI, + UCP_TIBETAN, + UCP_TIFINAGH, + UCP_UGARITIC, + UCP_YI, + // Unicode 5.0 + UCP_BALINESE, + UCP_CUNEIFORM, + UCP_NKO, + UCP_PHAGS_PA, + UCP_PHOENICIAN, + // Unicode 5.1 + UCP_CARIAN, + UCP_CHAM, + UCP_KAYAH_LI, + UCP_LEPCHA, + UCP_LYCIAN, + UCP_LYDIAN, + UCP_OL_CHIKI, + UCP_REJANG, + UCP_SAURASHTRA, + UCP_SUNDANESE, + UCP_VAI, + // Unicode 5.2 + UCP_AVESTAN, + UCP_BAMUM, + UCP_EGYPTIAN_HIEROGLYPHS, + UCP_IMPERIAL_ARAMAIC, + UCP_INSCRIPTIONAL_PAHLAVI, + UCP_INSCRIPTIONAL_PARTHIAN, + UCP_JAVANESE, + UCP_KAITHI, + UCP_LISU, + UCP_MEETEI_MAYEK, + UCP_OLD_SOUTH_ARABIAN, + UCP_OLD_TURKIC, + UCP_SAMARITAN, + UCP_TAI_THAM, + UCP_TAI_VIET, + // Unicode 6.0 + UCP_BATAK, + UCP_BRAHMI, + UCP_MANDAIC, + // Unicode 6.1 + UCP_CHAKMA, + UCP_MEROITIC_CURSIVE, + UCP_MEROITIC_HIEROGLYPHS, + UCP_MIAO, + UCP_SHARADA, + UCP_SORA_SOMPENG, + UCP_TAKRI, + // Unicode 7.0 + UCP_BASSA_VAH, + UCP_CAUCASIAN_ALBANIAN, + UCP_DUPLOYAN, + UCP_ELBASAN, + UCP_GRANTHA, + UCP_KHOJKI, + UCP_KHUDAWADI, + UCP_LINEAR_A, + UCP_MAHAJANI, + UCP_MANICHAEAN, + UCP_MENDE_KIKAKUI, + UCP_MODI, + UCP_MRO, + UCP_NABATAEAN, + UCP_OLD_NORTH_ARABIAN, + UCP_OLD_PERMIC, + UCP_PAHAWH_HMONG, + UCP_PALMYRENE, + UCP_PSALTER_PAHLAVI, + UCP_PAU_CIN_HAU, + UCP_SIDDHAM, + UCP_TIRHUTA, + UCP_WARANG_CITI + }; + + enum + { + UCP_MAX_CODEPOINT = 0x10FFFF + }; + + struct CharacterProperties + /// This structure holds the character properties + /// of an Unicode character. + { + CharacterCategory category; + CharacterType type; + Script script; + }; + + static void properties(int ch, CharacterProperties& props); + /// Return the Unicode character properties for the + /// character with the given Unicode value. + + static bool isSpace(int ch); + /// Returns true iff the given character is a separator. + + static bool isDigit(int ch); + /// Returns true iff the given character is a numeric character. + + static bool isPunct(int ch); + /// Returns true iff the given character is a punctuation character. + + static bool isAlpha(int ch); + /// Returns true iff the given character is a letter. + + static bool isLower(int ch); + /// Returns true iff the given character is a lowercase + /// character. + + static bool isUpper(int ch); + /// Returns true iff the given character is an uppercase + /// character. + + static int toLower(int ch); + /// If the given character is an uppercase character, + /// return its lowercase counterpart, otherwise return + /// the character. + + static int toUpper(int ch); + /// If the given character is a lowercase character, + /// return its uppercase counterpart, otherwise return + /// the character. +}; + + +// +// inlines +// +inline bool Unicode::isSpace(int ch) +{ + CharacterProperties props; + properties(ch, props); + return props.category == UCP_SEPARATOR; +} + + +inline bool Unicode::isDigit(int ch) +{ + CharacterProperties props; + properties(ch, props); + return props.category == UCP_NUMBER; +} + + +inline bool Unicode::isPunct(int ch) +{ + CharacterProperties props; + properties(ch, props); + return props.category == UCP_PUNCTUATION; +} + + +inline bool Unicode::isAlpha(int ch) +{ + CharacterProperties props; + properties(ch, props); + return props.category == UCP_LETTER; +} + + +inline bool Unicode::isLower(int ch) +{ + CharacterProperties props; + properties(ch, props); + return props.category == UCP_LETTER && props.type == UCP_LOWER_CASE_LETTER; +} + + +inline bool Unicode::isUpper(int ch) +{ + CharacterProperties props; + properties(ch, props); + return props.category == UCP_LETTER && props.type == UCP_UPPER_CASE_LETTER; +} + + +} // namespace Poco + + +#endif // Foundation_Unicode_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UnicodeConverter.h b/contrib/libs/poco/Foundation/include/Poco/UnicodeConverter.h new file mode 100644 index 0000000000..0733b67b7d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UnicodeConverter.h @@ -0,0 +1,141 @@ +// +// UnicodeConverter.h +// +// Library: Foundation +// Package: Text +// Module: UnicodeConverter +// +// Definition of the UnicodeConverter class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UnicodeConverter_INCLUDED +#define Foundation_UnicodeConverter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UTFString.h" + + +namespace Poco { + + +class Foundation_API UnicodeConverter + /// A convenience class that converts strings from + /// UTF-8 encoded std::strings to UTF-16 or UTF-32 encoded std::wstrings + /// and vice-versa. + /// + /// This class is mainly used for working with the Unicode Windows APIs + /// and probably won't be of much use anywhere else ??? +{ +public: + static void convert(const std::string& utf8String, UTF32String& utf32String); + /// Converts the given UTF-8 encoded string into an UTF-32 encoded wide string. + + static void convert(const char* utf8String, std::size_t length, UTF32String& utf32String); + /// Converts the given UTF-8 encoded character sequence into an UTF-32 encoded wide string. + + static void convert(const char* utf8String, UTF32String& utf32String); + /// Converts the given zero-terminated UTF-8 encoded character sequence into an UTF-32 encoded wide string. + + static void convert(const std::string& utf8String, UTF16String& utf16String); + /// Converts the given UTF-8 encoded string into an UTF-16 encoded wide string. + + static void convert(const char* utf8String, std::size_t length, UTF16String& utf16String); + /// Converts the given UTF-8 encoded character sequence into an UTF-16 encoded wide string. + + static void convert(const char* utf8String, UTF16String& utf16String); + /// Converts the given zero-terminated UTF-8 encoded character sequence into an UTF-16 encoded wide string. + + static void convert(const UTF16String& utf16String, std::string& utf8String); + /// Converts the given UTF-16 encoded wide string into an UTF-8 encoded string. + + static void convert(const UTF32String& utf32String, std::string& utf8String); + /// Converts the given UTF-32 encoded wide string into an UTF-8 encoded string. + + static void convert(const UTF16Char* utf16String, std::size_t length, std::string& utf8String); + /// Converts the given zero-terminated UTF-16 encoded wide character sequence into an UTF-8 encoded string. + + static void convert(const UTF32Char* utf16String, std::size_t length, std::string& utf8String); + /// Converts the given zero-terminated UTF-32 encoded wide character sequence into an UTF-8 encoded string. + + static void convert(const UTF16Char* utf16String, std::string& utf8String); + /// Converts the given UTF-16 encoded zero terminated character sequence into an UTF-8 encoded string. + + static void convert(const UTF32Char* utf32String, std::string& utf8String); + /// Converts the given UTF-32 encoded zero terminated character sequence into an UTF-8 encoded string. + + template <typename F, typename T> + static void toUTF32(const F& f, T& t) + { + convert(f, t); + } + + template <typename F, typename T> + static void toUTF32(const F& f, std::size_t l, T& t) + { + convert(f, l, t); + } + + template <typename F, typename T> + static void toUTF16(const F& f, T& t) + { + convert(f, t); + } + + template <typename F, typename T> + static void toUTF16(const F& f, std::size_t l, T& t) + { + convert(f, l, t); + } + + template <typename F, typename T> + static void toUTF8(const F& f, T& t) + { + convert(f, t); + } + + template <typename F, typename T> + static void toUTF8(const F& f, std::size_t l, T& t) + { + convert(f, l, t); + } + + template <typename T> + static T to(const char* pChar) + { + T utfStr; + Poco::UnicodeConverter::convert(pChar, utfStr); + return utfStr; + } + + + template <typename T> + static T to(const std::string& str) + { + T utfStr; + Poco::UnicodeConverter::convert(str, utfStr); + return utfStr; + } + + template <typename T> + static std::size_t UTFStrlen(const T* ptr) + /// Returns the length (in characters) of a zero-terminated UTF string. + { + if (ptr == 0) return 0; + const T* p; + for (p = ptr; *p; ++p); + return p - ptr; + } +}; + + +} // namespace Poco + + +#endif // Foundation_UnicodeConverter_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireCache.h b/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireCache.h new file mode 100644 index 0000000000..a2d58f6433 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireCache.h @@ -0,0 +1,73 @@ +// +// UniqueAccessExpireCache.h +// +// Library: Foundation +// Package: Cache +// Module: UniqueAccessExpireCache +// +// Definition of the UniqueAccessExpireCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UniqueAccessExpireCache_INCLUDED +#define Foundation_UniqueAccessExpireCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/UniqueAccessExpireStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class UniqueAccessExpireCache: public AbstractCache<TKey, TValue, UniqueAccessExpireStrategy<TKey, TValue>, TMutex, TEventMutex> + /// An UniqueAccessExpireCache caches entries for a given time span. In contrast + /// to ExpireCache which only allows to set a per cache expiration value, it allows to define + /// expiration per CacheEntry. + /// Each TValue object must thus offer the following method: + /// + /// const Poco::Timespan& getTimeout() const; + /// + /// which returns the relative timespan for how long the entry should be valid without being accessed! + /// The absolute expire timepoint is calculated as now() + getTimeout(). + /// Accessing an object will update this absolute expire timepoint. + /// You can use the Poco::AccessExpirationDecorator to add the getExpiration + /// method to values that do not have a getExpiration function. + /// + /// Be careful when using an UniqueAccessExpireCache. A cache is often used + /// like cache.has(x) followed by cache.get x). Note that it could happen + /// that the "has" call works, then the current execution thread gets descheduled, time passes, + /// the entry gets invalid, thus leading to an empty SharedPtr being returned + /// when "get" is invoked. +{ +public: + UniqueAccessExpireCache(): + AbstractCache<TKey, TValue, UniqueAccessExpireStrategy<TKey, TValue>, TMutex, TEventMutex>(UniqueAccessExpireStrategy<TKey, TValue>()) + { + } + + ~UniqueAccessExpireCache() + { + } + +private: + UniqueAccessExpireCache(const UniqueAccessExpireCache& aCache); + UniqueAccessExpireCache& operator = (const UniqueAccessExpireCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_UniqueAccessExpireCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireLRUCache.h b/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireLRUCache.h new file mode 100644 index 0000000000..6e7a366670 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireLRUCache.h @@ -0,0 +1,71 @@ +// +// UniqueAccessExpireLRUCache.h +// +// Library: Foundation +// Package: Cache +// Module: UniqueAccessExpireLRUCache +// +// Definition of the UniqueAccessExpireLRUCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UniqueAccessExpireLRUCache_INCLUDED +#define Foundation_UniqueAccessExpireLRUCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/StrategyCollection.h" +#include "Poco/UniqueAccessExpireStrategy.h" +#include "Poco/LRUStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class UniqueAccessExpireLRUCache: public AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue>, TMutex, TEventMutex> + /// A UniqueAccessExpireLRUCache combines LRU caching and time based per entry expire caching. + /// One can define for each cache entry a seperate timepoint + /// but also limit the size of the cache (per default: 1024). + /// Each TValue object must thus offer the following method: + /// + /// const Poco::Timespan& getTimeout() const; + /// + /// which returns the relative timespan for how long the entry should be valid without being accessed! + /// The absolute expire timepoint is calculated as now() + getTimeout(). + /// Accessing an object will update this absolute expire timepoint. + /// You can use the Poco::AccessExpirationDecorator to add the getExpiration + /// method to values that do not have a getExpiration function. +{ +public: + UniqueAccessExpireLRUCache(long cacheSize = 1024): + AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue>, TMutex, TEventMutex>(StrategyCollection<TKey, TValue>()) + { + this->_strategy.pushBack(new LRUStrategy<TKey, TValue>(cacheSize)); + this->_strategy.pushBack(new UniqueAccessExpireStrategy<TKey, TValue>()); + } + + ~UniqueAccessExpireLRUCache() + { + } + +private: + UniqueAccessExpireLRUCache(const UniqueAccessExpireLRUCache& aCache); + UniqueAccessExpireLRUCache& operator = (const UniqueAccessExpireLRUCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_UniqueAccessExpireLRUCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireStrategy.h b/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireStrategy.h new file mode 100644 index 0000000000..d20f2185e0 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UniqueAccessExpireStrategy.h @@ -0,0 +1,156 @@ +// +// UniqueAccessExpireStrategy.h +// +// Library: Foundation +// Package: Cache +// Module: UniqueAccessExpireStrategy +// +// Definition of the UniqueAccessExpireStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UniqueAccessExpireStrategy_INCLUDED +#define Foundation_UniqueAccessExpireStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/AbstractStrategy.h" +#include "Poco/Bugcheck.h" +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" +#include "Poco/EventArgs.h" +#include "Poco/UniqueExpireStrategy.h" +#include <set> +#include <map> + + +namespace Poco { + + +template < + class TKey, + class TValue +> +class UniqueAccessExpireStrategy: public AbstractStrategy<TKey, TValue> + /// An UniqueExpireStrategy implements time based expiration of cache entries. In contrast + /// to ExpireStrategy which only allows to set a per cache expiration value, it allows to define + /// expiration per CacheEntry. + /// Each TValue object must thus offer the following method: + /// + /// const Poco::Timestamp& getTimeout() const; + /// + /// which returns the timespan for how long an object will be valid without being accessed. +{ +public: + typedef std::pair<TKey, Timespan> KeyExpire; + typedef std::multimap<Timestamp, KeyExpire> TimeIndex; + typedef typename TimeIndex::iterator IndexIterator; + typedef typename TimeIndex::const_iterator ConstIndexIterator; + typedef std::map<TKey, IndexIterator> Keys; + typedef typename Keys::iterator Iterator; + +public: + UniqueAccessExpireStrategy() + /// Create an unique expire strategy. + { + } + + ~UniqueAccessExpireStrategy() + { + } + + void onAdd(const void*, const KeyValueArgs <TKey, TValue>& args) + { + // the expire value defines how many millisecs in the future the + // value will expire, even insert negative values! + Timestamp expire; + expire += args.value().getTimeout().totalMicroseconds(); + + IndexIterator it = _keyIndex.insert(std::make_pair(expire, std::make_pair(args.key(), args.value().getTimeout()))); + std::pair<Iterator, bool> stat = _keys.insert(std::make_pair(args.key(), it)); + if (!stat.second) + { + _keyIndex.erase(stat.first->second); + stat.first->second = it; + } + } + + void onRemove(const void*, const TKey& key) + { + Iterator it = _keys.find(key); + if (it != _keys.end()) + { + _keyIndex.erase(it->second); + _keys.erase(it); + } + } + + void onGet(const void*, const TKey& key) + { + // get updates the expiration time stamp + Iterator it = _keys.find(key); + if (it != _keys.end()) + { + KeyExpire ke = it->second->second; + // gen new absolute expire value + Timestamp expire; + expire += ke.second.totalMicroseconds(); + // delete old index + _keyIndex.erase(it->second); + IndexIterator itt = _keyIndex.insert(std::make_pair(expire, ke)); + // update iterator + it->second = itt; + } + } + + void onClear(const void*, const EventArgs& args) + { + _keys.clear(); + _keyIndex.clear(); + } + + void onIsValid(const void*, ValidArgs<TKey>& args) + { + Iterator it = _keys.find(args.key()); + if (it != _keys.end()) + { + Timestamp now; + if (it->second->first <= now) + { + args.invalidate(); + } + } + else //not found: probably removed by onReplace + args.invalidate(); + } + + void onReplace(const void*, std::set<TKey>& elemsToRemove) + { + // Note: replace only informs the cache which elements + // it would like to remove! + // it does not remove them on its own! + IndexIterator it = _keyIndex.begin(); + Timestamp now; + while (it != _keyIndex.end() && it->first < now) + { + elemsToRemove.insert(it->second.first); + ++it; + } + } + +protected: + Keys _keys; /// For faster replacement of keys, the iterator points to the _keyIndex map + TimeIndex _keyIndex; /// Maps time to key value +}; + + +} // namespace Poco + + +#endif // Foundation_UniqueAccessExpireStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UniqueExpireCache.h b/contrib/libs/poco/Foundation/include/Poco/UniqueExpireCache.h new file mode 100644 index 0000000000..613f9e215c --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UniqueExpireCache.h @@ -0,0 +1,72 @@ +// +// UniqueExpireCache.h +// +// Library: Foundation +// Package: Cache +// Module: UniqueExpireCache +// +// Definition of the UniqueExpireCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UniqueExpireCache_INCLUDED +#define Foundation_UniqueExpireCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/UniqueExpireStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class UniqueExpireCache: public AbstractCache<TKey, TValue, UniqueExpireStrategy<TKey, TValue>, TMutex, TEventMutex> + /// An UniqueExpireCache caches entries for a given time amount. In contrast + /// to ExpireCache which only allows to set a per cache expiration value, it allows to define + /// expiration per CacheEntry. + /// Each TValue object must thus offer the following method: + /// + /// const Poco::Timestamp& getExpiration() const; + /// + /// which returns the absolute timepoint when the entry will be invalidated. + /// Accessing an object will NOT update this absolute expire timepoint. + /// You can use the Poco::ExpirationDecorator to add the getExpiration + /// method to values that do not have a getExpiration function. + /// + /// Be careful when using an UniqueExpireCache. A cache is often used + /// like cache.has(x) followed by cache.get x). Note that it could happen + /// that the "has" call works, then the current execution thread gets descheduled, time passes, + /// the entry gets invalid, thus leading to an empty SharedPtr being returned + /// when "get" is invoked. +{ +public: + UniqueExpireCache(): + AbstractCache<TKey, TValue, UniqueExpireStrategy<TKey, TValue>, TMutex, TEventMutex>(UniqueExpireStrategy<TKey, TValue>()) + { + } + + ~UniqueExpireCache() + { + } + +private: + UniqueExpireCache(const UniqueExpireCache& aCache); + UniqueExpireCache& operator = (const UniqueExpireCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_UniqueExpireCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UniqueExpireLRUCache.h b/contrib/libs/poco/Foundation/include/Poco/UniqueExpireLRUCache.h new file mode 100644 index 0000000000..c59bf0f7a4 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UniqueExpireLRUCache.h @@ -0,0 +1,70 @@ +// +// UniqueExpireLRUCache.h +// +// Library: Foundation +// Package: Cache +// Module: UniqueExpireLRUCache +// +// Definition of the UniqueExpireLRUCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UniqueExpireLRUCache_INCLUDED +#define Foundation_UniqueExpireLRUCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/StrategyCollection.h" +#include "Poco/UniqueExpireStrategy.h" +#include "Poco/LRUStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue, + class TMutex = FastMutex, + class TEventMutex = FastMutex +> +class UniqueExpireLRUCache: public AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue>, TMutex, TEventMutex> + /// A UniqueExpireLRUCache combines LRU caching and time based per entry expire caching. + /// One can define for each cache entry a seperate timepoint + /// but also limit the size of the cache (per default: 1024). + /// Each TValue object must thus offer the following method: + /// + /// const Poco::Timestamp& getExpiration() const; + /// + /// which returns the absolute timepoint when the entry will be invalidated. + /// Accessing an object will NOT update this absolute expire timepoint. + /// You can use the Poco::ExpirationDecorator to add the getExpiration + /// method to values that do not have a getExpiration function. +{ +public: + UniqueExpireLRUCache(long cacheSize = 1024): + AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue>, TMutex, TEventMutex>(StrategyCollection<TKey, TValue>()) + { + this->_strategy.pushBack(new LRUStrategy<TKey, TValue>(cacheSize)); + this->_strategy.pushBack(new UniqueExpireStrategy<TKey, TValue>()); + } + + ~UniqueExpireLRUCache() + { + } + +private: + UniqueExpireLRUCache(const UniqueExpireLRUCache& aCache); + UniqueExpireLRUCache& operator = (const UniqueExpireLRUCache& aCache); +}; + + +} // namespace Poco + + +#endif // Foundation_UniqueExpireLRUCache_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/UniqueExpireStrategy.h b/contrib/libs/poco/Foundation/include/Poco/UniqueExpireStrategy.h new file mode 100644 index 0000000000..6ae79945b1 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/UniqueExpireStrategy.h @@ -0,0 +1,138 @@ +// +// UniqueExpireStrategy.h +// +// Library: Foundation +// Package: Cache +// Module: UniqueExpireStrategy +// +// Definition of the UniqueExpireStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_UniqueExpireStrategy_INCLUDED +#define Foundation_UniqueExpireStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/AbstractStrategy.h" +#include "Poco/Bugcheck.h" +#include "Poco/Timestamp.h" +#include "Poco/EventArgs.h" +#include <set> +#include <map> + + +namespace Poco { + + +template < + class TKey, + class TValue +> +class UniqueExpireStrategy: public AbstractStrategy<TKey, TValue> + /// An UniqueExpireStrategy implements time based expiration of cache entries. In contrast + /// to ExpireStrategy which only allows to set a per cache expiration value, it allows to define + /// expiration per CacheEntry. + /// Each TValue object must thus offer the following method: + /// + /// const Poco::Timestamp& getExpiration() const; + /// + /// which returns the absolute timepoint when the entry will be invalidated. +{ +public: + typedef std::multimap<Timestamp, TKey> TimeIndex; + typedef typename TimeIndex::iterator IndexIterator; + typedef typename TimeIndex::const_iterator ConstIndexIterator; + typedef std::map<TKey, IndexIterator> Keys; + typedef typename Keys::iterator Iterator; + +public: + UniqueExpireStrategy() + /// Create an unique expire strategy. + { + } + + ~UniqueExpireStrategy() + { + } + + void onAdd(const void*, const KeyValueArgs <TKey, TValue>& args) + { + // note: we have to insert even if the expire timepoint is in the past (for StrategyCollection classes to avoid inconsistency with LRU) + // no problem: will be removed with next get + const Timestamp& expire = args.value().getExpiration(); + IndexIterator it = _keyIndex.insert(std::make_pair(expire, args.key())); + std::pair<Iterator, bool> stat = _keys.insert(std::make_pair(args.key(), it)); + if (!stat.second) + { + _keyIndex.erase(stat.first->second); + stat.first->second = it; + } + } + + void onRemove(const void*, const TKey& key) + { + Iterator it = _keys.find(key); + if (it != _keys.end()) + { + _keyIndex.erase(it->second); + _keys.erase(it); + } + } + + void onGet(const void*, const TKey& key) + { + // get triggers no changes in an expire + } + + void onClear(const void*, const EventArgs& args) + { + _keys.clear(); + _keyIndex.clear(); + } + + void onIsValid(const void*, ValidArgs<TKey>& args) + { + Iterator it = _keys.find(args.key()); + if (it != _keys.end()) + { + Timestamp now; + if (it->second->first <= now) + { + args.invalidate(); + } + } + else //not found: probably removed by onReplace + args.invalidate(); + } + + void onReplace(const void*, std::set<TKey>& elemsToRemove) + { + // Note: replace only informs the cache which elements + // it would like to remove! + // it does not remove them on its own! + IndexIterator it = _keyIndex.begin(); + Timestamp now; + while (it != _keyIndex.end() && it->first < now) + { + elemsToRemove.insert(it->second); + ++it; + } + } + +protected: + Keys _keys; /// For faster replacement of keys, the iterator points to the _keyIndex map + TimeIndex _keyIndex; /// Maps time to key value +}; + + +} // namespace Poco + + +#endif // Foundation_UniqueExpireStrategy_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/ValidArgs.h b/contrib/libs/poco/Foundation/include/Poco/ValidArgs.h new file mode 100644 index 0000000000..7928a0fe8b --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/ValidArgs.h @@ -0,0 +1,74 @@ +// +// ValidArgs.h +// +// Library: Foundation +// Package: Cache +// Module: ValidArgs +// +// Definition of the ValidArgs class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_ValidArgs_INCLUDED +#define Foundation_ValidArgs_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template <class TKey> +class ValidArgs +{ +public: + ValidArgs(const TKey& key): + _key(key), + _isValid(true) + { + } + + ValidArgs(const ValidArgs& args): + _key(args._key), + _isValid(args._isValid) + { + } + + ~ValidArgs() + { + } + + const TKey& key() const + { + return _key; + } + + bool isValid() const + { + return _isValid; + } + + void invalidate() + { + _isValid = false; + } + +protected: + const TKey& _key; + bool _isValid; + +private: + ValidArgs& operator = (const ValidArgs& args); +}; + + +} // namespace Poco + + +#endif // Foundation_ValidArgs_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Version.h b/contrib/libs/poco/Foundation/include/Poco/Version.h new file mode 100644 index 0000000000..72dff0c412 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Version.h @@ -0,0 +1,41 @@ +// +// Version.h +// +// Library: Foundation +// Package: Core +// Module: Version +// +// Version information for the POCO C++ Libraries. +// +// Copyright (c) 2004-2016, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Version_INCLUDED +#define Foundation_Version_INCLUDED + + +// +// Version Information +// +// Since 1.6.0, we're using Semantic Versioning 2.0 +// (http://semver.org/spec/v2.0.0.html) +// +// Version format is 0xAABBCCDD, where +// - AA is the major version number, +// - BB is the minor version number, +// - CC is the patch version number, and +// - DD is the pre-release designation/number. +// The pre-release designation hex digits have a special meaning: +// 00: final/stable releases +// Dx: development releases +// Ax: alpha releases +// Bx: beta releases +// +#define POCO_VERSION 0x01090400 + + +#endif // Foundation_Version_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Void.h b/contrib/libs/poco/Foundation/include/Poco/Void.h new file mode 100644 index 0000000000..fa0cd31afd --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Void.h @@ -0,0 +1,73 @@ +// +// Void.h +// +// Library: Foundation +// Package: Core +// Module: Void +// +// Definition of the Void class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Void_INCLUDED +#define Foundation_Void_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Void + /// A dummy class with value-type semantics, + /// mostly useful as a template argument. + /// + /// This class is typically used together with ActiveMethod, + /// if no argument or return value is needed. +{ +public: + Void(); + /// Creates the Void. + + Void(const Void& v); + /// Creates the Void from another Void. + /// + /// The philosophical aspects of this operation + /// remain undiscussed for now. + + ~Void(); + /// Destroys the Void. + + Void& operator = (const Void& v); + /// Assigns another void. + + bool operator ==(const Void& v) const; + /// Will return always true due to Voids having no members. + + bool operator !=(const Void& v) const; + /// Will return always false due to Voids having no members. +}; + + +inline bool Void::operator ==(const Void& /*v*/) const +{ + return true; +} + + +inline bool Void::operator !=(const Void& /*v*/) const +{ + return false; +} + + +} // namespace Poco + + +#endif // Foundation_Void_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Windows1250Encoding.h b/contrib/libs/poco/Foundation/include/Poco/Windows1250Encoding.h new file mode 100644 index 0000000000..c40a428848 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Windows1250Encoding.h @@ -0,0 +1,52 @@ +// +// Windows1250Encoding.h +// +// Library: Foundation +// Package: Text +// Module: Windows1250Encoding +// +// Definition of the Windows1250Encoding class. +// +// Copyright (c) 2005-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Windows1250Encoding_INCLUDED +#define Foundation_Windows1250Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Windows1250Encoding: public TextEncoding + /// Windows Codepage 1250 text encoding. + /// Based on: http://msdn.microsoft.com/en-us/goglobal/cc305143 +{ +public: + Windows1250Encoding(); + ~Windows1250Encoding(); + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Windows1250Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Windows1251Encoding.h b/contrib/libs/poco/Foundation/include/Poco/Windows1251Encoding.h new file mode 100644 index 0000000000..87510a9d9d --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Windows1251Encoding.h @@ -0,0 +1,52 @@ +// +// Windows1251Encoding.h +// +// Library: Foundation +// Package: Text +// Module: Windows1251Encoding +// +// Definition of the Windows1251Encoding class. +// +// Copyright (c) 2005-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Windows1251Encoding_INCLUDED +#define Foundation_Windows1251Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Windows1251Encoding: public TextEncoding + /// Windows Codepage 1251 text encoding. + /// Based on: http://msdn.microsoft.com/en-us/goglobal/cc305144 +{ +public: + Windows1251Encoding(); + ~Windows1251Encoding(); + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Windows1251Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/Windows1252Encoding.h b/contrib/libs/poco/Foundation/include/Poco/Windows1252Encoding.h new file mode 100644 index 0000000000..a5e2901412 --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/Windows1252Encoding.h @@ -0,0 +1,51 @@ +// +// Windows1252Encoding.h +// +// Library: Foundation +// Package: Text +// Module: Windows1252Encoding +// +// Definition of the Windows1252Encoding class. +// +// Copyright (c) 2005-2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_Windows1252Encoding_INCLUDED +#define Foundation_Windows1252Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Windows1252Encoding: public TextEncoding + /// Windows Codepage 1252 text encoding. +{ +public: + Windows1252Encoding(); + ~Windows1252Encoding(); + const char* canonicalName() const; + bool isA(const std::string& encodingName) const; + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + int queryConvert(const unsigned char* bytes, int length) const; + int sequenceLength(const unsigned char* bytes, int length) const; + +private: + static const char* _names[]; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Windows1252Encoding_INCLUDED diff --git a/contrib/libs/poco/Foundation/include/Poco/WindowsConsoleChannel.h b/contrib/libs/poco/Foundation/include/Poco/WindowsConsoleChannel.h new file mode 100644 index 0000000000..b395c26d0a --- /dev/null +++ b/contrib/libs/poco/Foundation/include/Poco/WindowsConsoleChannel.h @@ -0,0 +1,183 @@ +// +// WindowsConsoleChannel.h +// +// Library: Foundation +// Package: Logging +// Module: WindowsConsoleChannel +// +// Definition of the WindowsConsoleChannel class. +// +// Copyright (c) 2007, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef Foundation_WindowsConsoleChannel_INCLUDED +#define Foundation_WindowsConsoleChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Mutex.h" +#include "Poco/UnWindows.h" + + +namespace Poco { + + +class Foundation_API WindowsConsoleChannel: public Channel + /// A channel that writes to the Windows console. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// If POCO has been compiled with POCO_WIN32_UTF8, + /// log messages are assumed to be UTF-8 encoded, and + /// are converted to UTF-16 prior to writing them to the + /// console. This is the main difference to the ConsoleChannel + /// class, which cannot handle UTF-8 encoded messages on Windows. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is contained + /// in the text. + /// + /// Only available on Windows platforms. +{ +public: + WindowsConsoleChannel(); + /// Creates the WindowsConsoleChannel. + + void log(const Message& msg); + /// Logs the given message to the channel's stream. + +protected: + ~WindowsConsoleChannel(); + +private: + HANDLE _hConsole; + bool _isFile; +}; + + +class Foundation_API WindowsColorConsoleChannel: public Channel + /// A channel that writes to the Windows console. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// If POCO has been compiled with POCO_WIN32_UTF8, + /// log messages are assumed to be UTF-8 encoded, and + /// are converted to UTF-16 prior to writing them to the + /// console. This is the main difference to the ConsoleChannel + /// class, which cannot handle UTF-8 encoded messages on Windows. + /// + /// Messages can be colored depending on priority. + /// + /// To enable message coloring, set the "enableColors" + /// property to true (default). Furthermore, colors can be + /// configured by setting the following properties + /// (default values are given in parenthesis): + /// + /// * traceColor (gray) + /// * debugColor (gray) + /// * informationColor (default) + /// * noticeColor (default) + /// * warningColor (yellow) + /// * errorColor (lightRed) + /// * criticalColor (lightRed) + /// * fatalColor (lightRed) + /// + /// The following color values are supported: + /// + /// * default + /// * black + /// * red + /// * green + /// * brown + /// * blue + /// * magenta + /// * cyan + /// * gray + /// * darkgray + /// * lightRed + /// * lightGreen + /// * yellow + /// * lightBlue + /// * lightMagenta + /// * lightCyan + /// * white + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is contained + /// in the text. + /// + /// Only available on Windows platforms. +{ +public: + WindowsColorConsoleChannel(); + /// Creates the WindowsConsoleChannel. + + void log(const Message& msg); + /// Logs the given message to the channel's stream. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name. + /// + /// The following properties are supported: + /// * enableColors: Enable or disable colors. + /// * traceColor: Specify color for trace messages. + /// * debugColor: Specify color for debug messages. + /// * informationColor: Specify color for information messages. + /// * noticeColor: Specify color for notice messages. + /// * warningColor: Specify color for warning messages. + /// * errorColor: Specify color for error messages. + /// * criticalColor: Specify color for critical messages. + /// * fatalColor: Specify color for fatal messages. + /// + /// See the class documentation for a list of supported color values. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + /// See setProperty() for a description of the supported + /// properties. + +protected: + enum Color + { + CC_BLACK = 0x0000, + CC_RED = 0x0004, + CC_GREEN = 0x0002, + CC_BROWN = 0x0006, + CC_BLUE = 0x0001, + CC_MAGENTA = 0x0005, + CC_CYAN = 0x0003, + CC_GRAY = 0x0007, + CC_DARKGRAY = 0x0008, + CC_LIGHTRED = 0x000C, + CC_LIGHTGREEN = 0x000A, + CC_YELLOW = 0x000E, + CC_LIGHTBLUE = 0x0009, + CC_LIGHTMAGENTA = 0x000D, + CC_LIGHTCYAN = 0x000B, + CC_WHITE = 0x000F + }; + + ~WindowsColorConsoleChannel(); + WORD parseColor(const std::string& color) const; + std::string formatColor(WORD color) const; + void initColors(); + +private: + bool _enableColors; + HANDLE _hConsole; + bool _isFile; + WORD _colors[9]; +}; + + +} // namespace Poco + + +#endif // Foundation_WindowsConsoleChannel_INCLUDED |