diff --git a/Builds/VisualStudio2012/RippleD.vcxproj b/Builds/VisualStudio2012/RippleD.vcxproj index f2097bbc20..d9845c3ae0 100644 --- a/Builds/VisualStudio2012/RippleD.vcxproj +++ b/Builds/VisualStudio2012/RippleD.vcxproj @@ -1515,12 +1515,6 @@ true true - - true - true - true - true - true true @@ -2497,7 +2491,6 @@ - diff --git a/Builds/VisualStudio2012/RippleD.vcxproj.filters b/Builds/VisualStudio2012/RippleD.vcxproj.filters index e5df7b624b..ab5e19a0ae 100644 --- a/Builds/VisualStudio2012/RippleD.vcxproj.filters +++ b/Builds/VisualStudio2012/RippleD.vcxproj.filters @@ -1002,9 +1002,6 @@ [2] Old Ripple\ripple_core\nodestore\backend - - [2] Old Ripple\ripple_core\nodestore\backend - [2] Old Ripple\ripple_core\nodestore\backend @@ -2274,9 +2271,6 @@ [2] Old Ripple\ripple_core\nodestore\backend - - [2] Old Ripple\ripple_core\nodestore\backend - [2] Old Ripple\ripple_core\nodestore\backend diff --git a/src/beast/Builds/VisualStudio2012/beast.vcxproj b/src/beast/Builds/VisualStudio2012/beast.vcxproj index ee11c79c21..e8a152c307 100644 --- a/src/beast/Builds/VisualStudio2012/beast.vcxproj +++ b/src/beast/Builds/VisualStudio2012/beast.vcxproj @@ -110,9 +110,12 @@ + + + @@ -136,22 +139,11 @@ - - - - - - - - - - - @@ -165,10 +157,7 @@ - - - @@ -185,6 +174,7 @@ + @@ -265,19 +255,15 @@ - - - - @@ -299,24 +285,16 @@ - - - - - - - - @@ -363,7 +341,6 @@ - @@ -391,14 +368,6 @@ - - - - - - - - @@ -446,6 +415,12 @@ true + + true + true + true + true + true true @@ -476,6 +451,12 @@ true true + + true + true + true + true + true @@ -814,12 +795,6 @@ true - - true - true - true - true - true true @@ -938,12 +913,6 @@ true true - - true - true - true - true - true true @@ -1244,12 +1213,6 @@ true true - - true - true - true - true - true true @@ -1376,27 +1339,6 @@ true true - - - true - true - true - true - - - true - true - true - true - - - - true - true - true - true - - true diff --git a/src/beast/Builds/VisualStudio2012/beast.vcxproj.filters b/src/beast/Builds/VisualStudio2012/beast.vcxproj.filters index aa2c106050..0b081079a1 100644 --- a/src/beast/Builds/VisualStudio2012/beast.vcxproj.filters +++ b/src/beast/Builds/VisualStudio2012/beast.vcxproj.filters @@ -68,10 +68,10 @@ beast_core - beast\http\crypto\impl\sha2 + beast\crypto\impl\sha2 - beast\http\crypto\impl\sha2 + beast\crypto\impl\sha2 scripts @@ -135,18 +135,6 @@ {69e28551-92ea-420b-a465-75ed248e3b59} - - {62b1f8e3-79e4-46cc-b3fb-a12754aef249} - - - {1170f2bc-2456-410a-ab2b-c45f6ed37b9e} - - - {4834218f-f13f-41bc-a8a0-50314a3a99a3} - - - {15a98fee-1b52-45eb-9480-514b8750d755} - {cbf5f5a3-5d66-4b6d-996d-20ed14b41793} @@ -195,12 +183,6 @@ {91538dcf-b219-4c80-9861-bb4949089775} - - {2f5b95a8-1adf-4319-8464-ddc2b2e03f0b} - - - {bf498396-2e1f-4903-be68-3053ba439af5} - {c0724499-ab69-40c3-90e2-65242dbd2eaa} @@ -294,15 +276,6 @@ {30b0fdfb-02b6-47dd-bdd9-ffc1f57e1f2c} - - {9c1ef4c4-5623-4500-859f-12d6ce5ae362} - - - {fc3d3f14-9ba1-43e4-b086-cbbd2f63b944} - - - {44489531-f44a-439a-a6ea-d32c252b1e8b} - {df4f2935-13a1-4afe-90cc-d86472ec2466} @@ -315,14 +288,20 @@ {04f27818-7843-4ef3-967c-1761dc892342} + + {9c1ef4c4-5623-4500-859f-12d6ce5ae362} + + + {fc3d3f14-9ba1-43e4-b086-cbbd2f63b944} + + + {44489531-f44a-439a-a6ea-d32c252b1e8b} + beast_core - - beast_core\containers - beast_core\containers @@ -350,9 +329,6 @@ beast_core\containers - - beast_core\containers - beast_core\containers @@ -392,9 +368,6 @@ beast_core\maths - - beast_core\maths - beast_core\maths @@ -407,9 +380,6 @@ beast_core\memory - - beast_core\memory - beast_core\misc @@ -575,21 +545,6 @@ beast_core\memory - - beast_core\memory - - - beast_core\memory - - - beast_core\memory - - - beast_core\memory - - - beast_core\containers - beast_core\threads @@ -599,33 +554,15 @@ beast_core\diagnostic - - beast_core\maths - beast_core\diagnostic - - beast_crypto - - - beast_core\containers - beast_core\files beast_core\diagnostic - - beast_core\memory - - - beast_db - - - beast_db\keyvalue - beast_sqlite @@ -731,9 +668,6 @@ beast_core\thread - - beast_core\thread - beast_core\thread @@ -752,12 +686,6 @@ beast_asio\system - - beast_extras\traits - - - beast_extras - beast_core\system @@ -776,30 +704,6 @@ beast_core\system - - beast\intrusive - - - beast\intrusive - - - beast\mpl - - - beast\mpl - - - beast\mpl - - - beast\mpl - - - beast\mpl - - - beast\mpl - beast_asio\async @@ -914,9 +818,6 @@ beast_asio\http - - beast\mpl - beast_asio\basics @@ -932,15 +833,6 @@ beast_core\diagnostic - - beast_crypto\math - - - beast_crypto\math - - - beast_crypto\math - beast_core\memory @@ -1004,12 +896,6 @@ beast\intrusive - - beast\intrusive - - - beast\mpl - beast\http\impl\http-parser @@ -1091,17 +977,14 @@ beast - - beast\intrusive - beast - beast\http\crypto\impl\sha2 + beast\crypto\impl\sha2 - beast\http\crypto + beast\crypto beast_asio\async @@ -1273,23 +1156,14 @@ beast\asio - beast\http\crypto + beast\crypto beast\smart_ptr - - beast\stl - beast\stl - - beast\stl - - - beast\stl - beast @@ -1338,11 +1212,23 @@ beast + + beast\threads + + + beast\intrusive + + + beast\crypto + + + beast\crypto + + + beast\crypto + - - beast_core\containers - beast_core\containers @@ -1385,9 +1271,6 @@ beast_core\maths - - beast_core\maths - beast_core\maths @@ -1589,12 +1472,6 @@ beast_core\diagnostic - - beast_db - - - beast_db\keyvalue - beast_sqlite @@ -1652,9 +1529,6 @@ beast_core\thread - - beast_core\thread - beast_core\thread @@ -1733,9 +1607,6 @@ beast_asio\http - - beast_crypto - beast_core @@ -1751,15 +1622,6 @@ beast_core\diagnostic - - beast_crypto\math - - - beast_crypto\math - - - beast_extras - beast\net @@ -1806,19 +1668,19 @@ beast\http\impl - beast\http\crypto\impl\sha2 + beast\crypto\impl\sha2 - beast\http\crypto\impl\sha2 + beast\crypto\impl\sha2 - beast\http\crypto\impl\sha2 + beast\crypto\impl\sha2 - beast\http\crypto + beast\crypto - beast\http\crypto\impl + beast\crypto\impl beast\chrono\impl @@ -1890,7 +1752,7 @@ beast\asio\impl - beast\http\crypto\impl + beast\crypto\impl beast\smart_ptr\impl @@ -1916,6 +1778,12 @@ beast\insight\impl + + beast\crypto\impl + + + beast\crypto\impl + diff --git a/src/beast/TODO.txt b/src/beast/TODO.txt index 965d1721e4..32bdb06ae4 100644 --- a/src/beast/TODO.txt +++ b/src/beast/TODO.txt @@ -52,8 +52,6 @@ BEAST TODO - Rename include guards to boost style, e.g. BEAST_THROW_H_INCLUDED -- Decide if we should get rid of AtomicCounter, AtomicFlag, AtomicPointer, AtomicState - - Clean up CacheLine, StaticObject - Clean up ConcurrentObject diff --git a/src/beast/beast/Crypto.h b/src/beast/beast/Crypto.h index 379e172e3b..c84425be51 100644 --- a/src/beast/beast/Crypto.h +++ b/src/beast/beast/Crypto.h @@ -20,8 +20,11 @@ #ifndef BEAST_CRYPTO_H_INCLUDED #define BEAST_CRYPTO_H_INCLUDED +#include "crypto/BinaryEncoding.h" #include "crypto/MurmurHash.h" #include "crypto/Sha256.h" +#include "crypto/UnsignedInteger.h" +#include "crypto/UnsignedIntegerCalc.h" #endif diff --git a/src/beast/beast/FixedArray.h b/src/beast/beast/FixedArray.h index e9d50488af..c82062f8ac 100644 --- a/src/beast/beast/FixedArray.h +++ b/src/beast/beast/FixedArray.h @@ -139,7 +139,8 @@ bool operator!= (FixedArray const& lhs, FixedArray const& rhs) template bool operator< (FixedArray const& lhs, FixedArray const& rhs) { - return std::lexicographical_compare (lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); + return std::lexicographical_compare ( + lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } template diff --git a/src/beast/beast/Intrusive.h b/src/beast/beast/Intrusive.h index 065b92c9dd..89a3ace3bd 100644 --- a/src/beast/beast/Intrusive.h +++ b/src/beast/beast/Intrusive.h @@ -20,8 +20,6 @@ #ifndef BEAST_INTRUSIVE_H_INCLUDED #define BEAST_INTRUSIVE_H_INCLUDED -#include "intrusive/ForwardList.h" -#include "intrusive/IntrusiveArray.h" #include "intrusive/List.h" #include "intrusive/LockFreeStack.h" diff --git a/src/beast/beast/MPL.h b/src/beast/beast/MPL.h index 3be24c673a..cd4d3eadeb 100644 --- a/src/beast/beast/MPL.h +++ b/src/beast/beast/MPL.h @@ -20,14 +20,6 @@ #ifndef BEAST_MPL_H_INCLUDED #define BEAST_MPL_H_INCLUDED -#include "mpl/AddConst.h" -#include "mpl/CopyConst.h" -#include "mpl/IfCond.h" #include "mpl/IsCallPossible.h" -#include "mpl/PointerToOther.h" -#include "mpl/RemoveConst.h" -#include "mpl/RemoveConstVolatile.h" -#include "mpl/RemoveReference.h" -#include "mpl/RemoveVolatile.h" #endif diff --git a/src/beast/beast/STL.h b/src/beast/beast/STL.h index 3a84b3486e..730eb22ebf 100644 --- a/src/beast/beast/STL.h +++ b/src/beast/beast/STL.h @@ -20,9 +20,6 @@ #ifndef BEAST_STL_H_INCLUDED #define BEAST_STL_H_INCLUDED -#include "stl/function.h" #include "stl/shared_ptr.h" -#include "stl/thread.h" -#include "stl/unique_ptr.h" #endif diff --git a/src/beast/beast/Threads.h b/src/beast/beast/Threads.h index 6c3859d9a6..bd7a9c814c 100644 --- a/src/beast/beast/Threads.h +++ b/src/beast/beast/Threads.h @@ -34,4 +34,6 @@ #include "threads/WaitableEvent.h" #include "threads/ScopedWrapperContext.h" +#include "threads/semaphore.h" + #endif diff --git a/src/beast/modules/beast_crypto/math/BinaryEncoding.h b/src/beast/beast/crypto/BinaryEncoding.h similarity index 99% rename from src/beast/modules/beast_crypto/math/BinaryEncoding.h rename to src/beast/beast/crypto/BinaryEncoding.h index d93691e4a7..0112160eb9 100644 --- a/src/beast/modules/beast_crypto/math/BinaryEncoding.h +++ b/src/beast/beast/crypto/BinaryEncoding.h @@ -20,5 +20,4 @@ #ifndef BEAST_CRYPTO_BINARYENCODING_H_INCLUDED #define BEAST_CRYPTO_BINARYENCODING_H_INCLUDED - #endif diff --git a/src/beast/beast/crypto/Crypto.cpp b/src/beast/beast/crypto/Crypto.cpp index 77a73390f9..5fa107022a 100644 --- a/src/beast/beast/crypto/Crypto.cpp +++ b/src/beast/beast/crypto/Crypto.cpp @@ -19,5 +19,9 @@ #include "BeastConfig.h" +#include "../../modules/beast_core/beast_core.h" // for UnitTest + +#include "impl/BinaryEncoding.cpp" #include "impl/MurmurHash.cpp" #include "impl/Sha256.cpp" +#include "impl/UnsignedInteger.cpp" diff --git a/src/beast/modules/beast_crypto/math/UnsignedInteger.h b/src/beast/beast/crypto/UnsignedInteger.h similarity index 96% rename from src/beast/modules/beast_crypto/math/UnsignedInteger.h rename to src/beast/beast/crypto/UnsignedInteger.h index 7756d584fe..09a87c74fe 100644 --- a/src/beast/modules/beast_crypto/math/UnsignedInteger.h +++ b/src/beast/beast/crypto/UnsignedInteger.h @@ -20,6 +20,15 @@ #ifndef BEAST_CRYPTO_UNSIGNEDINTEGER_H_INCLUDED #define BEAST_CRYPTO_UNSIGNEDINTEGER_H_INCLUDED +#include "../SafeBool.h" +#include "UnsignedIntegerCalc.h" +#include "MurmurHash.h" + +#include +#include + +namespace beast { + /** Represents a set of bits of fixed size. The data is stored in "canonical" format which is network (big endian) @@ -36,13 +45,13 @@ public: static std::size_t const size = Bytes; // The underlying integer type we use when converting to calculation format. - typedef uint32 IntCalcType; + typedef std::uint32_t IntCalcType; // The type of object resulting from a conversion to calculation format. typedef UnsignedIntegerCalc CalcType; // Standard container compatibility - typedef uint8 value_type; + typedef std::uint8_t value_type; typedef value_type* iterator; typedef value_type const* const_iterator; @@ -135,7 +144,8 @@ public: template static UnsignedInteger createFromInteger (UnsignedIntegralType value) { - static_bassert (Bytes >= sizeof (UnsignedIntegralType)); + static_assert (Bytes >= sizeof (UnsignedIntegralType), + "Bytes is too small."); UnsignedInteger result; value = toNetworkByteOrder (value); result.clear (); @@ -296,4 +306,6 @@ private: IntCalcType m_values [CalcCount]; }; +} + #endif diff --git a/src/beast/modules/beast_crypto/math/UnsignedIntegerCalc.h b/src/beast/beast/crypto/UnsignedIntegerCalc.h similarity index 98% rename from src/beast/modules/beast_crypto/math/UnsignedIntegerCalc.h rename to src/beast/beast/crypto/UnsignedIntegerCalc.h index 5bb7f0f4f6..de3ea63d7e 100644 --- a/src/beast/modules/beast_crypto/math/UnsignedIntegerCalc.h +++ b/src/beast/beast/crypto/UnsignedIntegerCalc.h @@ -20,22 +20,25 @@ #ifndef BEAST_CRYPTO_UNSIGNEDINTEGERCALC_H_INCLUDED #define BEAST_CRYPTO_UNSIGNEDINTEGERCALC_H_INCLUDED -namespace detail -{ +#include + +namespace beast { + +namespace detail { template struct DoubleWidthUInt; template <> -struct DoubleWidthUInt +struct DoubleWidthUInt { - typedef uint32 type; + typedef std::uint32_t type; }; template <> -struct DoubleWidthUInt +struct DoubleWidthUInt { - typedef uint64 type; + typedef std::uint64_t type; }; } @@ -427,4 +430,6 @@ private: UInt* m_values; }; +} + #endif diff --git a/src/beast/modules/beast_crypto/math/BinaryEncoding.cpp b/src/beast/beast/crypto/impl/BinaryEncoding.cpp similarity index 98% rename from src/beast/modules/beast_crypto/math/BinaryEncoding.cpp rename to src/beast/beast/crypto/impl/BinaryEncoding.cpp index 198a6b7b86..dfdca1bcd6 100644 --- a/src/beast/modules/beast_crypto/math/BinaryEncoding.cpp +++ b/src/beast/beast/crypto/impl/BinaryEncoding.cpp @@ -17,6 +17,14 @@ */ //============================================================================== +#include "../BinaryEncoding.h" +#include "../UnsignedInteger.h" + +#include +#include + +namespace beast { + /** Generic algorithms for base encoding and decoding. */ class BinaryEncoding { @@ -393,3 +401,5 @@ public: }; static BinaryEncodingTests BinaryEncodingTests; + +} diff --git a/src/beast/modules/beast_crypto/math/UnsignedInteger.cpp b/src/beast/beast/crypto/impl/UnsignedInteger.cpp similarity index 96% rename from src/beast/modules/beast_crypto/math/UnsignedInteger.cpp rename to src/beast/beast/crypto/impl/UnsignedInteger.cpp index 40b079d061..2cd246257c 100644 --- a/src/beast/modules/beast_crypto/math/UnsignedInteger.cpp +++ b/src/beast/beast/crypto/impl/UnsignedInteger.cpp @@ -3,6 +3,10 @@ This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco + Portions are Copyright (c) 2013 the authors listed at the following URL, + and/or the authors of referenced articles or incorporated external code: + http://en.literateprograms.org/Arbitrary-precision_integer_arithmetic_(C)?action=history&offset=20100923155004 + Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. @@ -17,7 +21,13 @@ */ //============================================================================== -//------------------------------------------------------------------------------ +#include "../UnsignedInteger.h" + +namespace beast { + +namespace multiprecsion { + +#if 0 /* Copyright (c) 2013 the authors listed at the following URL, and/or the authors of referenced articles or incorporated external code: @@ -41,15 +51,11 @@ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - Retrieved from: http://en.literateprograms.org/Arbitrary-precision_integer_arithmetic_(C)?oldid=16902 */ -namespace multiprecsion -{ - -#if 0 -//------------------------------------------------------------------------------ +// +// Retrieved from: http://en.literateprograms.org/Arbitrary-precision_integer_arithmetic_(C)?oldid=16902 +// typedef unsigned short component_t; typedef unsigned long double_component_t; @@ -394,3 +400,5 @@ private: }; static UnsignedIntegerTests unsignedIntegerTests; + +} diff --git a/src/beast/beast/insight/Collector.h b/src/beast/beast/insight/Collector.h index da923d5fe5..9d379307cc 100644 --- a/src/beast/beast/insight/Collector.h +++ b/src/beast/beast/insight/Collector.h @@ -20,8 +20,7 @@ #ifndef BEAST_INSIGHT_COLLECTOR_H_INCLUDED #define BEAST_INSIGHT_COLLECTOR_H_INCLUDED -#include "../stl/function.h" -#include "../stl/shared_ptr.h" +#include #include "Counter.h" #include "Event.h" diff --git a/src/beast/beast/insight/Counter.h b/src/beast/beast/insight/Counter.h index ecffa911e9..4e78013384 100644 --- a/src/beast/beast/insight/Counter.h +++ b/src/beast/beast/insight/Counter.h @@ -20,9 +20,9 @@ #ifndef BEAST_INSIGHT_COUNTER_H_INCLUDED #define BEAST_INSIGHT_COUNTER_H_INCLUDED -#include "CounterImpl.h" +#include -#include "../stl/shared_ptr.h" +#include "CounterImpl.h" namespace beast { namespace insight { @@ -52,7 +52,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Counter (shared_ptr const& impl) + explicit Counter (std::shared_ptr const& impl) : m_impl (impl) { } @@ -100,7 +100,7 @@ public: /** @} */ private: - shared_ptr m_impl; + std::shared_ptr m_impl; }; } diff --git a/src/beast/beast/insight/CounterImpl.h b/src/beast/beast/insight/CounterImpl.h index 047a988198..963151490c 100644 --- a/src/beast/beast/insight/CounterImpl.h +++ b/src/beast/beast/insight/CounterImpl.h @@ -20,16 +20,19 @@ #ifndef BEAST_INSIGHT_COUNTERIMPL_H_INCLUDED #define BEAST_INSIGHT_COUNTERIMPL_H_INCLUDED +#include +#include + namespace beast { namespace insight { class Counter; -class CounterImpl : public enable_shared_from_this +class CounterImpl : public std::enable_shared_from_this { public: typedef int64 value_type; - typedef beast::function HandlerType; + typedef std::function HandlerType; virtual ~CounterImpl () = 0; virtual void increment (value_type amount) = 0; diff --git a/src/beast/beast/insight/Event.h b/src/beast/beast/insight/Event.h index a892c780b6..7c822fed7e 100644 --- a/src/beast/beast/insight/Event.h +++ b/src/beast/beast/insight/Event.h @@ -20,9 +20,9 @@ #ifndef BEAST_INSIGHT_EVENT_H_INCLUDED #define BEAST_INSIGHT_EVENT_H_INCLUDED -#include "EventImpl.h" +#include -#include "../stl/shared_ptr.h" +#include "EventImpl.h" namespace beast { namespace insight { @@ -53,7 +53,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Event (shared_ptr const& impl) + explicit Event (std::shared_ptr const& impl) : m_impl (impl) { } @@ -69,7 +69,7 @@ public: } private: - shared_ptr m_impl; + std::shared_ptr m_impl; }; } diff --git a/src/beast/beast/insight/EventImpl.h b/src/beast/beast/insight/EventImpl.h index ef93a2334c..3e84fe4260 100644 --- a/src/beast/beast/insight/EventImpl.h +++ b/src/beast/beast/insight/EventImpl.h @@ -20,12 +20,14 @@ #ifndef BEAST_INSIGHT_EVENTIMPL_H_INCLUDED #define BEAST_INSIGHT_EVENTIMPL_H_INCLUDED +#include + namespace beast { namespace insight { class Event; -class EventImpl : public enable_shared_from_this +class EventImpl : public std::enable_shared_from_this { public: typedef uint64 value_type; diff --git a/src/beast/beast/insight/Gauge.h b/src/beast/beast/insight/Gauge.h index 16fc484fd1..70fff9b05d 100644 --- a/src/beast/beast/insight/Gauge.h +++ b/src/beast/beast/insight/Gauge.h @@ -20,9 +20,9 @@ #ifndef BEAST_INSIGHT_GAUGE_H_INCLUDED #define BEAST_INSIGHT_GAUGE_H_INCLUDED -#include "GaugeImpl.h" +#include -#include "../stl/shared_ptr.h" +#include "GaugeImpl.h" namespace beast { namespace insight { @@ -54,7 +54,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Gauge (shared_ptr const& impl) + explicit Gauge (std::shared_ptr const& impl) : m_impl (impl) { } @@ -118,7 +118,7 @@ public: /** @} */ private: - shared_ptr m_impl; + std::shared_ptr m_impl; }; } diff --git a/src/beast/beast/insight/GaugeImpl.h b/src/beast/beast/insight/GaugeImpl.h index 0e26cb47e5..50ff9b5866 100644 --- a/src/beast/beast/insight/GaugeImpl.h +++ b/src/beast/beast/insight/GaugeImpl.h @@ -25,12 +25,12 @@ namespace insight { class Gauge; -class GaugeImpl : public enable_shared_from_this +class GaugeImpl : public std::enable_shared_from_this { public: typedef uint64 value_type; typedef int64 difference_type; - typedef beast::function HandlerType; + typedef std::function HandlerType; virtual ~GaugeImpl () = 0; virtual void set (value_type value) = 0; diff --git a/src/beast/beast/insight/Hook.h b/src/beast/beast/insight/Hook.h index 06ef844907..3b45992e3a 100644 --- a/src/beast/beast/insight/Hook.h +++ b/src/beast/beast/insight/Hook.h @@ -42,13 +42,13 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Hook (shared_ptr const& impl) + explicit Hook (std::shared_ptr const& impl) : m_impl (impl) { } private: - shared_ptr m_impl; + std::shared_ptr m_impl; }; } diff --git a/src/beast/beast/insight/HookImpl.h b/src/beast/beast/insight/HookImpl.h index cbbf371849..6c8cda2a0e 100644 --- a/src/beast/beast/insight/HookImpl.h +++ b/src/beast/beast/insight/HookImpl.h @@ -20,16 +20,17 @@ #ifndef BEAST_INSIGHT_HOOKIMPL_H_INCLUDED #define BEAST_INSIGHT_HOOKIMPL_H_INCLUDED -#include "../stl/shared_ptr.h" +#include +#include namespace beast { namespace insight { -class HookImpl : public enable_shared_from_this +class HookImpl : public std::enable_shared_from_this { public: - typedef beast::function HandlerType; - + typedef std::function HandlerType; + virtual ~HookImpl () = 0; }; diff --git a/src/beast/beast/insight/Meter.h b/src/beast/beast/insight/Meter.h index bf2090c1d9..bc7c72f9b7 100644 --- a/src/beast/beast/insight/Meter.h +++ b/src/beast/beast/insight/Meter.h @@ -51,7 +51,7 @@ public: factory function in the Collector interface. @see Collector. */ - explicit Meter (shared_ptr const& impl) + explicit Meter (std::shared_ptr const& impl) : m_impl (impl) { } @@ -89,7 +89,7 @@ public: /** @} */ private: - shared_ptr m_impl; + std::shared_ptr m_impl; }; } diff --git a/src/beast/beast/insight/MeterImpl.h b/src/beast/beast/insight/MeterImpl.h index 057bd155dd..ca3fffaa55 100644 --- a/src/beast/beast/insight/MeterImpl.h +++ b/src/beast/beast/insight/MeterImpl.h @@ -20,16 +20,19 @@ #ifndef BEAST_INSIGHT_METERIMPL_H_INCLUDED #define BEAST_INSIGHT_METERIMPL_H_INCLUDED +#include +#include + namespace beast { namespace insight { class Meter; -class MeterImpl : public enable_shared_from_this +class MeterImpl : public std::enable_shared_from_this { public: typedef uint64 value_type; - typedef beast::function HandlerType; + typedef std::function HandlerType; virtual ~MeterImpl () = 0; virtual void increment (value_type amount) = 0; diff --git a/src/beast/beast/insight/NullCollector.h b/src/beast/beast/insight/NullCollector.h index af1f22d6be..d0b117b2e4 100644 --- a/src/beast/beast/insight/NullCollector.h +++ b/src/beast/beast/insight/NullCollector.h @@ -29,7 +29,7 @@ namespace insight { class NullCollector : public Collector { public: - static shared_ptr New (); + static std::shared_ptr New (); }; } diff --git a/src/beast/beast/insight/StatsDCollector.h b/src/beast/beast/insight/StatsDCollector.h index 931c478f93..33a8682066 100644 --- a/src/beast/beast/insight/StatsDCollector.h +++ b/src/beast/beast/insight/StatsDCollector.h @@ -39,7 +39,7 @@ public: @param prefix A string pre-pended before each metric name. @param journal Destination for logging output. */ - static shared_ptr New (IPAddress const& address, + static std::shared_ptr New (IPAddress const& address, std::string const& prefix, Journal journal); }; diff --git a/src/beast/beast/insight/impl/NullCollector.cpp b/src/beast/beast/insight/impl/NullCollector.cpp index f1ab857f65..0539d783a9 100644 --- a/src/beast/beast/insight/impl/NullCollector.cpp +++ b/src/beast/beast/insight/impl/NullCollector.cpp @@ -112,27 +112,27 @@ public: Hook make_hook (HookImpl::HandlerType const&) { - return Hook (make_shared ()); + return Hook (std::make_shared ()); } Counter make_counter (std::string const&) { - return Counter (make_shared ()); + return Counter (std::make_shared ()); } Event make_event (std::string const&) { - return Event (make_shared ()); + return Event (std::make_shared ()); } Gauge make_gauge (std::string const&) { - return Gauge (make_shared ()); + return Gauge (std::make_shared ()); } Meter make_meter (std::string const&) { - return Meter (make_shared ()); + return Meter (std::make_shared ()); } }; @@ -140,9 +140,9 @@ public: //------------------------------------------------------------------------------ -shared_ptr NullCollector::New () +std::shared_ptr NullCollector::New () { - return beast::make_shared (); + return std::make_shared (); } } diff --git a/src/beast/beast/insight/impl/StatsDCollector.cpp b/src/beast/beast/insight/impl/StatsDCollector.cpp index 6e958ae604..c92690fa85 100644 --- a/src/beast/beast/insight/impl/StatsDCollector.cpp +++ b/src/beast/beast/insight/impl/StatsDCollector.cpp @@ -24,8 +24,10 @@ #include #include #include +#include #include +#include #include #include @@ -57,7 +59,7 @@ class StatsDHookImpl public: StatsDHookImpl ( HandlerType const& handler, - beast::shared_ptr const& impl); + std::shared_ptr const& impl); ~StatsDHookImpl (); @@ -66,7 +68,7 @@ public: private: StatsDHookImpl& operator= (StatsDHookImpl const&); - beast::shared_ptr m_impl; + std::shared_ptr m_impl; HandlerType m_handler; }; @@ -78,7 +80,7 @@ class StatsDCounterImpl { public: StatsDCounterImpl (std::string const& name, - beast::shared_ptr const& impl); + std::shared_ptr const& impl); ~StatsDCounterImpl (); @@ -86,14 +88,13 @@ public: void set_handler (HandlerType const& handler); void flush (); - void do_increment (CounterImpl::value_type amount, - shared_ptr const& ptr); + void do_increment (CounterImpl::value_type amount); void do_process (); private: StatsDCounterImpl& operator= (StatsDCounterImpl const&); - beast::shared_ptr m_impl; + std::shared_ptr m_impl; std::string m_name; CounterImpl::value_type m_value; bool m_dirty; @@ -107,20 +108,19 @@ class StatsDEventImpl { public: StatsDEventImpl (std::string const& name, - beast::shared_ptr const& impl); + std::shared_ptr const& impl); ~StatsDEventImpl (); void notify (EventImpl::value_type value); - void do_notify (EventImpl::value_type value, - shared_ptr const& ptr); + void do_notify (EventImpl::value_type value); void do_process (); private: StatsDEventImpl& operator= (StatsDEventImpl const&); - beast::shared_ptr m_impl; + std::shared_ptr m_impl; std::string m_name; }; @@ -132,7 +132,7 @@ class StatsDGaugeImpl { public: StatsDGaugeImpl (std::string const& name, - beast::shared_ptr const& impl); + std::shared_ptr const& impl); ~StatsDGaugeImpl (); @@ -141,16 +141,14 @@ public: void set_handler (HandlerType const& handler); void flush (); - void do_set (GaugeImpl::value_type value, - shared_ptr const& ptr); - void do_increment (GaugeImpl::difference_type amount, - shared_ptr const& ptr); + void do_set (GaugeImpl::value_type value); + void do_increment (GaugeImpl::difference_type amount); void do_process (); private: StatsDGaugeImpl& operator= (StatsDGaugeImpl const&); - beast::shared_ptr m_impl; + std::shared_ptr m_impl; std::string m_name; GaugeImpl::value_type m_last_value; GaugeImpl::value_type m_value; @@ -166,7 +164,7 @@ class StatsDMeterImpl { public: explicit StatsDMeterImpl (std::string const& name, - beast::shared_ptr const& impl); + std::shared_ptr const& impl); ~StatsDMeterImpl (); @@ -174,14 +172,13 @@ public: void set_handler (HandlerType const& handler); void flush (); - void do_increment (MeterImpl::value_type amount, - shared_ptr const& ptr); + void do_increment (MeterImpl::value_type amount); void do_process (); private: StatsDMeterImpl& operator= (StatsDMeterImpl const&); - beast::shared_ptr m_impl; + std::shared_ptr m_impl; std::string m_name; MeterImpl::value_type m_value; bool m_dirty; @@ -192,7 +189,7 @@ private: class StatsDCollectorImp : public StatsDCollector - , public beast::enable_shared_from_this + , public std::enable_shared_from_this { private: enum @@ -219,7 +216,7 @@ private: State m_state; // Must come last for order of init - beast::thread m_thread; + std::thread m_thread; static boost::asio::ip::udp::endpoint to_endpoint ( IPAddress const &address) @@ -263,31 +260,31 @@ public: Hook make_hook (HookImpl::HandlerType const& handler) { - return Hook (beast::make_shared ( + return Hook (std::make_shared ( handler, shared_from_this ())); } Counter make_counter (std::string const& name) { - return Counter (beast::make_shared ( + return Counter (std::make_shared ( name, shared_from_this ())); } Event make_event (std::string const& name) { - return Event (beast::make_shared ( + return Event (std::make_shared ( name, shared_from_this ())); } Gauge make_gauge (std::string const& name) { - return Gauge (beast::make_shared ( + return Gauge (std::make_shared ( name, shared_from_this ())); } Meter make_meter (std::string const& name) { - return Meter (beast::make_shared ( + return Meter (std::make_shared ( name, shared_from_this ())); } @@ -327,9 +324,9 @@ public: void post_buffer (std::string&& buffer) { - m_io_service.dispatch (boost::bind ( + m_io_service.dispatch (std::bind ( &StatsDCollectorImp::do_post_buffer, this, - boost::move (buffer))); + std::move (buffer))); } void on_send (boost::system::error_code ec, std::size_t) @@ -443,7 +440,7 @@ public: //------------------------------------------------------------------------------ StatsDHookImpl::StatsDHookImpl (HandlerType const& handler, - beast::shared_ptr const& impl) + std::shared_ptr const& impl) : m_impl (impl) , m_handler (handler) { @@ -463,7 +460,7 @@ void StatsDHookImpl::do_process () //------------------------------------------------------------------------------ StatsDCounterImpl::StatsDCounterImpl (std::string const& name, - beast::shared_ptr const& impl) + std::shared_ptr const& impl) : m_impl (impl) , m_name (name) , m_value (0) @@ -479,8 +476,10 @@ StatsDCounterImpl::~StatsDCounterImpl () void StatsDCounterImpl::increment (CounterImpl::value_type amount) { - m_impl->get_io_service().dispatch (boost::bind ( - &StatsDCounterImpl::do_increment, this, amount, shared_from_this())); + m_impl->get_io_service().dispatch (std::bind ( + &StatsDCounterImpl::do_increment, + std::static_pointer_cast ( + shared_from_this ()), amount)); } void StatsDCounterImpl::set_handler (HandlerType const& handler) @@ -504,8 +503,7 @@ void StatsDCounterImpl::flush () } } -void StatsDCounterImpl::do_increment (CounterImpl::value_type amount, - shared_ptr const&) +void StatsDCounterImpl::do_increment (CounterImpl::value_type amount) { m_value += amount; m_dirty = true; @@ -521,7 +519,7 @@ void StatsDCounterImpl::do_process () //------------------------------------------------------------------------------ StatsDEventImpl::StatsDEventImpl (std::string const& name, - beast::shared_ptr const& impl) + std::shared_ptr const& impl) : m_impl (impl) , m_name (name) { @@ -533,12 +531,13 @@ StatsDEventImpl::~StatsDEventImpl () void StatsDEventImpl::notify (EventImpl::value_type value) { - m_impl->get_io_service().dispatch (boost::bind ( - &StatsDEventImpl::do_notify, this, value, shared_from_this())); + m_impl->get_io_service().dispatch (std::bind ( + &StatsDEventImpl::do_notify, + std::static_pointer_cast ( + shared_from_this ()), value)); } -void StatsDEventImpl::do_notify (EventImpl::value_type value, - shared_ptr const&) +void StatsDEventImpl::do_notify (EventImpl::value_type value) { std::stringstream ss; ss << @@ -552,7 +551,7 @@ void StatsDEventImpl::do_notify (EventImpl::value_type value, //------------------------------------------------------------------------------ StatsDGaugeImpl::StatsDGaugeImpl (std::string const& name, - beast::shared_ptr const& impl) + std::shared_ptr const& impl) : m_impl (impl) , m_name (name) , m_last_value (0) @@ -569,14 +568,18 @@ StatsDGaugeImpl::~StatsDGaugeImpl () void StatsDGaugeImpl::set (GaugeImpl::value_type value) { - m_impl->get_io_service().dispatch (boost::bind ( - &StatsDGaugeImpl::do_set, this, value, shared_from_this ())); + m_impl->get_io_service().dispatch (std::bind ( + &StatsDGaugeImpl::do_set, + std::static_pointer_cast ( + shared_from_this ()), value)); } void StatsDGaugeImpl::increment (GaugeImpl::difference_type amount) { - m_impl->get_io_service().dispatch (boost::bind ( - &StatsDGaugeImpl::do_increment, this, amount, shared_from_this())); + m_impl->get_io_service().dispatch (std::bind ( + &StatsDGaugeImpl::do_increment, + std::static_pointer_cast ( + shared_from_this ()), amount)); } void StatsDGaugeImpl::set_handler (HandlerType const& handler) @@ -599,8 +602,7 @@ void StatsDGaugeImpl::flush () } } -void StatsDGaugeImpl::do_set (GaugeImpl::value_type value, - shared_ptr const&) +void StatsDGaugeImpl::do_set (GaugeImpl::value_type value) { m_value = value; @@ -611,8 +613,7 @@ void StatsDGaugeImpl::do_set (GaugeImpl::value_type value, } } -void StatsDGaugeImpl::do_increment (GaugeImpl::difference_type amount, - shared_ptr const& ptr) +void StatsDGaugeImpl::do_increment (GaugeImpl::difference_type amount) { GaugeImpl::value_type value (m_value); @@ -631,7 +632,7 @@ void StatsDGaugeImpl::do_increment (GaugeImpl::difference_type amount, : std::abs (amount); } - do_set (value, ptr); + do_set (value); } void StatsDGaugeImpl::do_process () @@ -644,7 +645,7 @@ void StatsDGaugeImpl::do_process () //------------------------------------------------------------------------------ StatsDMeterImpl::StatsDMeterImpl (std::string const& name, - beast::shared_ptr const& impl) + std::shared_ptr const& impl) : m_impl (impl) , m_name (name) , m_value (0) @@ -660,8 +661,10 @@ StatsDMeterImpl::~StatsDMeterImpl () void StatsDMeterImpl::increment (MeterImpl::value_type amount) { - m_impl->get_io_service().dispatch (boost::bind ( - &StatsDMeterImpl::do_increment, this, amount, shared_from_this())); + m_impl->get_io_service().dispatch (std::bind ( + &StatsDMeterImpl::do_increment, + std::static_pointer_cast ( + shared_from_this ()), amount)); } void StatsDMeterImpl::set_handler (HandlerType const& handler) @@ -685,8 +688,7 @@ void StatsDMeterImpl::flush () } } -void StatsDMeterImpl::do_increment (MeterImpl::value_type amount, - shared_ptr const&) +void StatsDMeterImpl::do_increment (MeterImpl::value_type amount) { m_value += amount; m_dirty = true; @@ -703,10 +705,10 @@ void StatsDMeterImpl::do_process () //------------------------------------------------------------------------------ -shared_ptr StatsDCollector::New ( +std::shared_ptr StatsDCollector::New ( IPAddress const& address, std::string const& prefix, Journal journal) { - return beast::make_shared ( + return std::make_shared ( address, prefix, journal); } diff --git a/src/beast/beast/intrusive/ForwardList.h b/src/beast/beast/intrusive/ForwardList.h deleted file mode 100644 index 86264d0d2f..0000000000 --- a/src/beast/beast/intrusive/ForwardList.h +++ /dev/null @@ -1,448 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_INTRUSIVE_FORWARDLIST_H_INCLUDED -#define BEAST_INTRUSIVE_FORWARDLIST_H_INCLUDED - -#include "../Config.h" - -#include "PointerTraits.h" - -#include "../MPL.h" - -#include - -// Ideas based on boost - -namespace beast { -namespace intrusive { - -//------------------------------------------------------------------------------ - -namespace detail { - -// Holds the size field -struct SizeHolder -{ -public: - typedef std::size_t size_type; - - inline size_type size () const noexcept - { - return m_size; - } - - inline void set (size_type new_size) noexcept - { - m_size = new_size; - } - - inline void increment () noexcept - { - ++m_size; - } - - inline void decrement () noexcept - { - --m_size; - } - -private: - size_type m_size; -}; - -} - -//------------------------------------------------------------------------------ - -template -struct ForwardListNode -{ - typedef typename PointerTraits ::template rebind_pointer ::type node_ptr; - - node_ptr next; -}; - -//------------------------------------------------------------------------------ - -// Provides value_traits for when T derives from Node -template -struct DerivedValueTraits -{ - typedef NodeTraits node_traits; - typedef T value_type; - typedef typename node_traits::node node; - typedef typename node_traits::node_ptr node_ptr; - typedef typename node_traits::const_node_ptr const_node_ptr; - typedef typename mpl::PointerToOther ::type pointer; - typedef typename mpl::PointerToOther ::type const_pointer; - typedef typename PointerTraits ::reference reference; - typedef typename PointerTraits ::reference const_reference; - - static node_ptr to_node_ptr (reference value) - { - return node_ptr (&value); - } - - static const_node_ptr to_node_ptr (const_reference value) - { - return node_ptr (&value); - } - - static pointer to_value_ptr (node_ptr const& n) - { - return pointer (&static_cast (*n)); - } - - static const_pointer to_value_ptr (const_node_ptr const &n) - { - return const_pointer (&static_cast (*n)); - } -}; - -//------------------------------------------------------------------------------ - -template -struct ForwardListNodeTraits -{ - typedef ForwardListNode node; - - typedef typename PointerTraits :: - template rebind_pointer node_ptr; - - typedef typename PointerTraits :: - template rebind_pointer const_node_ptr; - - static node_ptr get_next (const_node_ptr const& n) - { - return n->m_next; - } - - static node_ptr get_next (node_ptr const& n) - { - return n->m_next; - } - - static void set_next (node_ptr const& n, node_ptr const& next) - { - n->m_next = next; - } -}; - -//------------------------------------------------------------------------------ - -template -class ForwardListIterator - : public std::iterator < - std::forward_iterator_tag, - typename Container::value_type, - typename Container::difference_type, - typename mpl::IfCond ::type, - typename mpl::IfCond ::type> -{ -protected: - typedef typename Container::value_traits value_traits; - typedef typename Container::node_traits node_traits; - typedef typename node_traits::node node; - typedef typename node_traits::node_ptr node_ptr; - typedef typename PointerTraits :: - template rebind_pointer ::type void_pointer; - -public: - typedef typename Container::value_type value_type; - typedef typename mpl::IfCond ::type pointer; - typedef typename mpl::IfCond ::type reference; - - ForwardListIterator () - : m_node () - { - } - - explicit ForwardListIterator (ForwardListIterator const& other) - : m_node (other.pointed_node ()) - { - } - - node_ptr const& pointed_node () const noexcept - { - return m_node; - } - - ForwardListIterator& operator= (node_ptr const& node) - { - m_node = node; - return static_cast (*this); - } - - ForwardListIterator& operator++ () - { - m_node = node_traits::get_next (m_node); - return static_cast (*this); - } - - ForwardListIterator operator++ (int) - { - ForwardListIterator result (*this); - m_node = node_traits::get_next (m_node); - return result; - } - - friend bool operator== (ForwardListIterator const& lhs, - ForwardListIterator const& rhs) - { - return lhs.m_node == rhs.m_node; - } - - friend bool operator!= (ForwardListIterator const& lhs, - ForwardListIterator const& rhs) - { - return ! (lhs == rhs); - } - - reference operator* () const - { - return *this->operator-> (); - } - - pointer operator-> () const - { - return value_traits::to_value_ptr (m_node); - } - -private: - node_ptr m_node; -}; - -//------------------------------------------------------------------------------ - -template -class ForwardListAlgorithms -{ -public: - typedef typename NodeTraits::node node; - typedef typename NodeTraits::node_ptr node_ptr; - typedef typename NodeTraits::const_node_ptr const_node_ptr; - typedef NodeTraits node_traits; - - static void init (node_ptr const& n) - { - NodeTraits::set_next (n, node_ptr()); - } - - static bool unique (const_node_ptr const& this_node) - { - node_ptr next = NodeTraits::get_next (this_node); - return !next || next == this_node; - } - - static void link_after (node_ptr const& prev_node, node_ptr const& this_node) - { - NodeTraits::set_next (this_node, NodeTraits::get_next (prev_node)); - NodeTraits::set_next (prev_node, this_node); - } - - static void unlink_after (node_ptr const& prev_node) - { - const_node_ptr this_node (NodeTraits::get_next (prev_node)); - NodeTraits::set_next (prev_node, NodeTraits::get_next (this_node)); - } -}; - -//------------------------------------------------------------------------------ - -/** Singly-linked intrusive list. */ -template -class ForwardList -{ -public: - typedef DerivedValueTraits > - value_traits; - typedef typename value_traits::pointer pointer; - typedef typename value_traits::const_pointer const_pointer; - typedef typename PointerTraits ::element_type value_type; - typedef typename PointerTraits ::reference reference; - typedef typename PointerTraits ::const_reference const_reference; - typedef typename PointerTraits ::difference_type difference_type; - typedef std::size_t size_type; - typedef ForwardListIterator iterator; - typedef ForwardListIterator const_iterator; - typedef typename value_traits::node_traits node_traits; - typedef typename node_traits::node node; - typedef typename node_traits::node_ptr node_ptr; - typedef typename node_traits::const_node_ptr const_node_ptr; - typedef ForwardListAlgorithms node_algorithms; - - typedef node Node; - -private: - typedef detail::SizeHolder size_traits; - - void default_construct () - { - get_size_traits ().set (size_type (0)); - node_algorithms::init (this->get_root_node ()); - } - - node_ptr get_end_node () - { - return node_ptr (); - } - - const_node_ptr get_end_node () const - { - return const_node_ptr (); - } - - node_ptr get_root_node () - { - return PointerTraits ::pointer_to (m_root); - } - - const_node_ptr get_root_node () const - { - return PointerTraits ::pointer_to (m_root); - } - - size_traits& get_size_traits () noexcept - { - return m_size; - } - - size_traits const& get_size_traits () const noexcept - { - return m_size; - } - - static node_ptr uncast (const_node_ptr const& ptr) - { - return PointerTraits ::const_cast_from (ptr); - } - -public: - ForwardList () - { - default_construct (); - } - - void clear () - { - default_construct (); - } - - void push_front (reference value) - { - node_ptr this_node (value_traits::to_node_ptr (value)); - node_algorithms::link_after (this->get_root_node (), this_node); - this->get_size_traits ().increment (); - } - - void pop_front () - { - //node_ptr this_node (node_traits::get_next (this->get_root ())); - node_algorithms::unlink_after (this->get_root_node ()); - this->get_size_traits ().decrement (); - } - - reference front () - { - return *value_traits::to_value_ptr (node_traits::get_next (this->get_root_node ())); - } - - const_reference front () const - { - return *value_traits::to_value_ptr (uncat (node_traits::get_next (this->get_root_node ()))); - } - - iterator begin () - { - return iterator (node_traits::get_next (this->get_root_node (), this)); - } - - const_iterator begin () const - { - return const_iterator (node_traits::get_next (this->get_root_node (), this)); - } - - const_iterator cbegin () const - { - return this->begin (); - } - - iterator end () - { - return iterator (this->get_end_node (), this); - } - - const_iterator end () const - { - return const_iterator (this->get_end_node (), this); - } - - const_iterator cend () const - { - return this->end (); - } - - iterator before_begin () - { - return iterator (this->get_root_node (), this); - } - - const_iterator before_begin () const - { - return const_iterator (this->get_root_node (), this); - } - - const_iterator cbefore_begin () const - { - return before_begin (); - } - - bool empty () const - { - return node_algorithms::unique (this->get_root_node ()); - } - - iterator iterator_to (reference value) - { - return iterator (value_traits::to_node_ptr (value), this); - } - - const_iterator iterator_to (const_reference value) const - { - return const_iterator (value_traits::to_node_ptr (const_cast (value)), this); - } - -private: - node m_root; - size_traits m_size; -}; - -} -} - -#endif diff --git a/src/beast/beast/intrusive/IntrusiveArray.h b/src/beast/beast/intrusive/IntrusiveArray.h deleted file mode 100644 index 53fbe0b057..0000000000 --- a/src/beast/beast/intrusive/IntrusiveArray.h +++ /dev/null @@ -1,187 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_INTRUSIVE_INTRUSIVEARRAY_H_INCLUDED -#define BEAST_INTRUSIVE_INTRUSIVEARRAY_H_INCLUDED - -#include "../Config.h" - -#include -#include -#include -#include - -namespace beast { - -/** A run-time fixed size array that references outside storage. - The interface tries to follow std::vector as closely as possible within - the limitations of a fixed size and unowned storage. -*/ -template -class IntrusiveArray -{ -private: - T* m_begin; - T* m_end; - -public: - typedef T value_type; - typedef T* iterator; - typedef T const* const_iterator; - typedef T& reference; - typedef T const& const_reference; - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; - - // Calling methods on a default constructed - // array results in undefined behavior! - // - IntrusiveArray () - : m_begin (nullptr), m_end (nullptr) - { } - IntrusiveArray (T* begin, T* end) - : m_begin (begin), m_end (end) - { } - IntrusiveArray (IntrusiveArray const& other) - : m_begin (other.m_begin), m_end (other.m_end) - { } - IntrusiveArray (std::vector const& v) - : m_begin (&v.front()), m_end (&v.back()+1) - { } - IntrusiveArray (std::vector & v) - : m_begin (&v.front()), m_end (&v.back()+1) - { } - IntrusiveArray& operator= (IntrusiveArray const& other) - { - m_begin = other.m_begin; - m_end = other.m_end; - return *this; - } - - // iterators - iterator begin() { return m_begin; } - const_iterator begin() const { return m_begin; } - const_iterator cbegin() const { return m_begin; } - iterator end() { return m_end; } - const_iterator end() const { return m_end; } - const_iterator cend() const { return m_end; } - - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - reverse_iterator rbegin() { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); } - reverse_iterator rend() { return reverse_iterator(begin()); } - const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } - const_reverse_iterator crend() const { return const_reverse_iterator(begin()); } - - reference operator[](size_type i) - { - bassert (i < size()); - return m_begin[i]; - } - - const_reference operator[](size_type i) const - { - bassert (i < size()); - return m_begin[i]; - } - - reference at(size_type i) { rangecheck(i); return m_begin[i]; } - const_reference at(size_type i) const { rangecheck(i); return m_begin[i]; } - - reference front() { return m_begin[0]; } - reference back() { return m_end[-1]; } - const_reference front () const { return m_begin; } - const_reference back() const { return m_end[-1]; } - - size_type size() const { return std::distance (m_begin, m_end); } - bool empty() const { return m_begin == m_end; } - - T const* data() const { return m_begin; } - T* data() { return m_begin; } - T* c_array() { return m_begin; } - - void assign (T const& value) { fill (value); } - - void fill (T const& value) - { - std::fill_n (begin(), size(), value); - } - - void clear () - { - fill (T ()); - } - - void rangecheck (size_type i) - { - if (i >= size()) - throw std::out_of_range ("IntrusiveArray<>: index out of range"); - } -}; - -//------------------------------------------------------------------------------ - -template -bool operator== (IntrusiveArray const& lhs, IntrusiveArray const& rhs) -{ - if ((lhs.begin() == rhs.begin()) && (lhs.end() == rhs.end())) - return true; - if (lhs.size() != rhs.size()) - return false; - return std::equal (lhs.begin(), lhs.end(), rhs.begin()); -} - -template -bool operator!= (IntrusiveArray const& lhs, IntrusiveArray const& rhs) -{ - return !(lhs==rhs); -} - -template -bool operator< (IntrusiveArray const& lhs, IntrusiveArray const& rhs) -{ - if ((lhs.begin() == rhs.begin()) && (lhs.end() == rhs.end())) - return false; - return std::lexicographical_compare (lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); -} - -template -bool operator> (IntrusiveArray const& lhs, IntrusiveArray const& rhs) -{ - return rhs -bool operator<= (IntrusiveArray const& lhs, IntrusiveArray const& rhs) -{ - return !(rhs -bool operator>= (IntrusiveArray const& lhs, IntrusiveArray const& rhs) -{ - return !(lhs +#include namespace beast { template class List; -namespace detail +namespace detail { + +/** Copy `const` attribute from T to U if present. */ +/** @{ */ +template +struct CopyConst { + typedef typename std::remove_const ::type type; +}; + +template +struct CopyConst +{ + typedef typename std::remove_const ::type const type; +}; +/** @} */ // This is the intrusive portion of the doubly linked list. // One derivation per list that the object may appear on @@ -62,11 +74,11 @@ class ListIterator : public std::iterator < std::bidirectional_iterator_tag, std::size_t> { public: - typedef typename mpl::CopyConst::type - value_type; - typedef value_type* pointer; - typedef value_type& reference; - typedef std::size_t size_type; + typedef typename detail::CopyConst < + N, typename N::value_type>::type value_type; + typedef value_type* pointer; + typedef value_type& reference; + typedef std::size_t size_type; ListIterator (N* node = nullptr) noexcept : m_node (node) diff --git a/src/beast/beast/intrusive/LockFreeStack.h b/src/beast/beast/intrusive/LockFreeStack.h index 7de727fd94..c4452bec0e 100644 --- a/src/beast/beast/intrusive/LockFreeStack.h +++ b/src/beast/beast/intrusive/LockFreeStack.h @@ -20,11 +20,12 @@ #ifndef BEAST_INTRUSIVE_LOCKFREESTACK_H_INCLUDED #define BEAST_INTRUSIVE_LOCKFREESTACK_H_INCLUDED -#include -#include "../mpl/IfCond.h" #include "../Atomic.h" #include "../Uncopyable.h" +#include +#include + namespace beast { //------------------------------------------------------------------------------ @@ -35,23 +36,24 @@ class LockFreeStackIterator std::forward_iterator_tag, typename Container::value_type, typename Container::difference_type, - typename mpl::IfCond ::type, - typename mpl::IfCond ::type> { protected: typedef typename Container::Node Node; - typedef typename mpl::IfCond ::type NodePtr; + typedef typename std::conditional < + IsConst, Node const*, Node*>::type NodePtr; public: typedef typename Container::value_type value_type; - typedef typename mpl::IfCond ::type pointer; - typedef typename mpl::IfCond ::type reference; diff --git a/src/beast/beast/intrusive/PointerTraits.h b/src/beast/beast/intrusive/PointerTraits.h deleted file mode 100644 index ccba95f91e..0000000000 --- a/src/beast/beast/intrusive/PointerTraits.h +++ /dev/null @@ -1,89 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_INTRUSIVE_POINTERTRAITS_H_INCLUDED -#define BEAST_INTRUSIVE_POINTERTRAITS_H_INCLUDED - -#include - -namespace beast { -namespace intrusive { - -// an unspecialized PointerTraits is ill-defined -template -struct PointerTraits; - -// specializations to remove cv-qualifiers -template -struct PointerTraits

: PointerTraits

{ }; -template -struct PointerTraits

: PointerTraits

{ }; -template -struct PointerTraits

: PointerTraits

{ }; -// specialization to remove a reference attribute -template -struct PointerTraits : PointerTraits

{ }; - -// specialization for raw pointers -template -struct PointerTraits -{ - typedef T element_type; - typedef T* pointer; - typedef T& reference; - typedef std::ptrdiff_t difference_type; - - template - struct rebind_pointer - { - typedef U* type; - }; - - static pointer pointer_to (reference r) - { - return static_cast ( - static_cast ( - const_cast ( - &reinterpret_cast ( - r)))); - } - - template - static pointer static_cast_from (U* u) - { - return static_cast (u); - } - - template - static pointer const_cast_from (U* u) - { - return const_cast (u); - } - - template - static pointer dynamic_cast_from (U* u) - { - return dynamic_cast (u); - } -}; - -} -} - -#endif diff --git a/src/beast/beast/mpl/AddConst.h b/src/beast/beast/mpl/AddConst.h deleted file mode 100644 index 3ab16e6b7d..0000000000 --- a/src/beast/beast/mpl/AddConst.h +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_MPL_ADDCONST_H_INCLUDED -#define BEAST_MPL_ADDCONST_H_INCLUDED - -#include "RemoveConst.h" - -// Ideas based on boost - -namespace beast { -namespace mpl { - -/** Add the `const` qualifier to a type. */ -template -struct AddConst -{ - typedef typename RemoveConst::type const type; -}; - -} -} - -#endif diff --git a/src/beast/beast/mpl/CopyConst.h b/src/beast/beast/mpl/CopyConst.h deleted file mode 100644 index a733ded884..0000000000 --- a/src/beast/beast/mpl/CopyConst.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_MPL_COPYCONST_H_INCLUDED -#define BEAST_MPL_COPYCONST_H_INCLUDED - -#include "RemoveConst.h" - -namespace beast { -namespace mpl { - -/** Copy `const` attribute from T to U if present. */ -/** @{ */ -template -struct CopyConst -{ - typedef typename RemoveConst::type type; -}; - -template -struct CopyConst -{ - typedef typename RemoveConst::type const type; -}; -/** @} */ - -} -} - -#endif diff --git a/src/beast/beast/mpl/IfCond.h b/src/beast/beast/mpl/IfCond.h deleted file mode 100644 index 44aad16137..0000000000 --- a/src/beast/beast/mpl/IfCond.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_MPL_IFCOND_H_INCLUDED -#define BEAST_MPL_IFCOND_H_INCLUDED - -namespace beast { -namespace mpl { - -// Ideas based on boost - -/** Select between T1 or T2 depending on Condition. */ -/** @{ */ -template -struct IfCond -{ - typedef T1 type; -}; - -template -struct IfCond -{ - typedef T2 type; -}; -/** @} */ - -} -} - -#endif diff --git a/src/beast/beast/mpl/PointerToOther.h b/src/beast/beast/mpl/PointerToOther.h deleted file mode 100644 index 8a82274f30..0000000000 --- a/src/beast/beast/mpl/PointerToOther.h +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_MPL_POINTERTOOTHERH_INCLUDED -#define BEAST_MPL_POINTERTOOTHERH_INCLUDED - -namespace beast { -namespace mpl { - -// Ideas based on boost - -/** Declares a type which is a pointer or smart pointer to U, depending on T. - This works for smart pointer containers with up to three template - parameters. More specializations can be added for containers with - more than three template parameters. -*/ -/** @{ */ -template -struct PointerToOther; - -template class SmartPointer> -struct PointerToOther , U> -{ - typedef SmartPointer type; -}; - -template class SmartPointer> -struct PointerToOther , U> -{ - typedef SmartPointer type; -}; - -template class SmartPointer> -struct PointerToOther , U> -{ - typedef SmartPointer type; -}; - -template -struct PointerToOther -{ - typedef U* type; -}; -/** @} */ - -} -} - -#endif diff --git a/src/beast/beast/mpl/RemoveConst.h b/src/beast/beast/mpl/RemoveConst.h deleted file mode 100644 index 86f58b9f36..0000000000 --- a/src/beast/beast/mpl/RemoveConst.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_MPL_REMOVECONST_H_INCLUDED -#define BEAST_MPL_REMOVECONST_H_INCLUDED - -// Ideas based on boost - -namespace beast { -namespace mpl { - -/** Remove the `const` qualifier from a type. */ -/** @{ */ -template -struct RemoveConst -{ - typedef T type; -}; - -template -struct RemoveConst -{ - typedef T type; -}; -/** @} */ - -} -} - -#endif diff --git a/src/beast/beast/mpl/RemoveConstVolatile.h b/src/beast/beast/mpl/RemoveConstVolatile.h deleted file mode 100644 index b320d507b6..0000000000 --- a/src/beast/beast/mpl/RemoveConstVolatile.h +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_MPL_REMOVECONSTVOLATILE_H_INCLUDED -#define BEAST_MPL_REMOVECONSTVOLATILE_H_INCLUDED - -#include "RemoveConst.h" -#include "RemoveVolatile.h" - -// Ideas based on boost - -namespace beast { -namespace mpl { - -/** Remove both the `const` and `volatile` qualifiers from a type. */ -template -struct RemoveConstVolatile -{ - typedef typename RemoveConst < - typename RemoveVolatile ::type - >::type type; -}; - -} -} - -#endif diff --git a/src/beast/beast/mpl/RemoveReference.h b/src/beast/beast/mpl/RemoveReference.h deleted file mode 100644 index c7b8d6d651..0000000000 --- a/src/beast/beast/mpl/RemoveReference.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_MPL_REMOVEREFERENCE_H_INCLUDED -#define BEAST_MPL_REMOVEREFERENCE_H_INCLUDED - -namespace beast { -namespace mpl { - -// Ideas based on boost - -/** Remove the reference qualifier from a type. */ -/** @{ */ -template -struct RemoveReference -{ - typedef T type; -}; - -template -struct RemoveReference -{ - typedef T type; -}; -/** @} */ - -} -} - -#endif diff --git a/src/beast/beast/mpl/RemoveVolatile.h b/src/beast/beast/mpl/RemoveVolatile.h deleted file mode 100644 index 5057a16bdd..0000000000 --- a/src/beast/beast/mpl/RemoveVolatile.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_MPL_REMOVEVOLATILE_H_INCLUDED -#define BEAST_MPL_REMOVEVOLATILE_H_INCLUDED - -// Ideas based on boost - -namespace beast { -namespace mpl { - -/** Remove the `volatile` qualifier from a type. */ -/** @{ */ -template -struct RemoveVolatile -{ - typedef T type; -}; - -template -struct RemoveVolatile -{ - typedef T type; -}; -/** @} */ - -} -} - -#endif diff --git a/src/beast/beast/net/BufferType.h b/src/beast/beast/net/BufferType.h index a94990a3bf..ae5c240042 100644 --- a/src/beast/beast/net/BufferType.h +++ b/src/beast/beast/net/BufferType.h @@ -20,7 +20,7 @@ #ifndef BEAST_NET_BASICS_BUFFERTYPE_H_INCLUDED #define BEAST_NET_BASICS_BUFFERTYPE_H_INCLUDED -#include "../mpl/IfCond.h" +#include namespace beast { @@ -34,13 +34,11 @@ template class BufferType { private: - typedef typename mpl::IfCond ::type pointer_type; + typedef typename std::conditional ::type pointer_type; - typedef typename mpl::IfCond ::type byte_type; + typedef typename std::conditional ::type byte_type; public: typedef std::size_t size_type; diff --git a/src/beast/beast/net/IPAddress.h b/src/beast/beast/net/IPAddress.h index b946eaf898..ef2616fae2 100644 --- a/src/beast/beast/net/IPAddress.h +++ b/src/beast/beast/net/IPAddress.h @@ -25,7 +25,6 @@ #include #include "../CStdInt.h" -#include "../mpl/IfCond.h" namespace std { @@ -115,7 +114,8 @@ public: class Proxy { public: - typedef typename mpl::IfCond ::type Pointer; + typedef typename std::conditional < + IsConst, uint32 const*, uint32*>::type Pointer; Proxy (int shift, Pointer value) : m_shift (shift) diff --git a/src/beast/beast/smart_ptr/SharedObject.h b/src/beast/beast/smart_ptr/SharedObject.h index 53de02c7a7..55266c978f 100644 --- a/src/beast/beast/smart_ptr/SharedObject.h +++ b/src/beast/beast/smart_ptr/SharedObject.h @@ -24,8 +24,9 @@ #ifndef BEAST_SHAREDOBJECT_H_INCLUDED #define BEAST_SHAREDOBJECT_H_INCLUDED +#include + #include "../Config.h" -#include "../Atomic.h" #include "../Uncopyable.h" namespace beast { @@ -71,7 +72,7 @@ public: This is done automatically by the smart pointer, but is public just in case it's needed for nefarious purposes. */ - inline void incReferenceCount() const noexcept + void incReferenceCount() const noexcept { ++refCount; } @@ -93,15 +94,16 @@ public: } /** Returns the object's current reference count. */ - inline int getReferenceCount() const noexcept + int getReferenceCount() const noexcept { - return refCount.get(); + return refCount.load(); } protected: //============================================================================== /** Creates the reference-counted object (with an initial ref count of zero). */ SharedObject() + : refCount (0) { } @@ -125,79 +127,12 @@ protected: */ void resetReferenceCount() noexcept { - refCount = 0; + refCount.store (0); } private: //============================================================================== - Atomic mutable refCount; -}; - -//============================================================================== -/** - Adds reference-counting to an object. - - This is effectively a version of the SharedObject class, but which - uses a non-atomic counter, and so is not thread-safe (but which will be more - efficient). - For more details on how to use it, see the SharedObject class notes. - - @see SharedObject, SharedPtr, SharedObjectArray -*/ -class BEAST_API SingleThreadedSharedObject : public Uncopyable -{ -public: - //============================================================================== - /** Increments the object's reference count. - - This is done automatically by the smart pointer, but is public just - in case it's needed for nefarious purposes. - */ - inline void incReferenceCount() noexcept - { - ++refCount; - } - - /** Decreases the object's reference count. - - If doDelete is true the object will be deleted when the reference - count drops to zero. The delete is performed using the regular - operator and does NOT go through the ContainerDeletePolicy. - - The return value indicates if the reference count dropped to zero, - so callers who know the derived type can use the ContainerDeletePolicy. - */ - inline void decReferenceCount () - { - bassert (getReferenceCount() > 0); - if (--refCount == 0) - destroy (); - } - - /** Returns the object's current reference count. */ - inline int getReferenceCount() const noexcept { return refCount; } - - -protected: - //============================================================================== - /** Creates the reference-counted object (with an initial ref count of zero). */ - SingleThreadedSharedObject() : refCount (0) {} - - /** Destructor. */ - virtual ~SingleThreadedSharedObject() - { - // it's dangerous to delete an object that's still referenced by something else! - bassert (getReferenceCount() == 0); - } - - virtual void destroy () const - { - delete this; - } - -private: - //============================================================================== - int refCount; + std::atomic mutable refCount; }; } diff --git a/src/beast/beast/stl/STL.cpp b/src/beast/beast/stl/STL.cpp index 2d46a5f9a9..24ed420bf1 100644 --- a/src/beast/beast/stl/STL.cpp +++ b/src/beast/beast/stl/STL.cpp @@ -19,7 +19,4 @@ #include "BeastConfig.h" -#include "function.h" #include "shared_ptr.h" -#include "thread.h" -#include "unique_ptr.h" diff --git a/src/beast/beast/stl/function.h b/src/beast/beast/stl/function.h deleted file mode 100644 index 2c769b76f1..0000000000 --- a/src/beast/beast/stl/function.h +++ /dev/null @@ -1,31 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_STL_FUNCTION_H_INCLUDED -#define BEAST_STL_FUNCTION_H_INCLUDED - -#include - -namespace beast { - -using boost::function; - -} - -#endif diff --git a/src/beast/beast/stl/thread.h b/src/beast/beast/stl/thread.h deleted file mode 100644 index 987f461cff..0000000000 --- a/src/beast/beast/stl/thread.h +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_STL_THREAD_H_INCLUDED -#define BEAST_STL_THREAD_H_INCLUDED - -#include - -namespace beast { - -using boost::thread; - -namespace this_thread { -using namespace boost::this_thread; -} - -} - -#endif diff --git a/src/beast/beast/stl/unique_ptr.h b/src/beast/beast/stl/unique_ptr.h deleted file mode 100644 index 24984cc4d4..0000000000 --- a/src/beast/beast/stl/unique_ptr.h +++ /dev/null @@ -1,255 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_STL_UNIQUE_PTR_H_INCLUDED -#define BEAST_STL_UNIQUE_PTR_H_INCLUDED - -#include "../Config.h" -#include "../Uncopyable.h" - -#ifndef BEAST_UNIQUE_PTR_USES_STL -# if BEAST_USE_CPLUSPLUS11 -# define BEAST_UNIQUE_PTR_USES_STL 1 -# else -# define BEAST_UNIQUE_PTR_USES_STL 0 -# endif -#endif - -#if BEAST_UNIQUE_PTR_USES_STL -# include -namespace beast { -using std::unique_ptr; -} - -#else - -namespace beast { - -template -class unique_ptr : public Uncopyable -{ -public: - //============================================================================== - /** Creates a unique_ptr containing a null pointer. */ - inline unique_ptr() - : object (nullptr) - { - } - - /** Creates a unique_ptr that owns the specified object. */ - inline unique_ptr (ObjectType* const objectToTakePossessionOf) - : object (objectToTakePossessionOf) - { - } - - /** Creates a unique_ptr that takes its pointer from another unique_ptr. - - Because a pointer can only belong to one unique_ptr, this transfers - the pointer from the other object to this one, and the other object is reset to - be a null pointer. - */ - unique_ptr (unique_ptr& objectToTransferFrom) - : object (objectToTransferFrom.object) - { - objectToTransferFrom.object = nullptr; - } - - /** Destructor. - This will delete the object that this unique_ptr currently refers to. - */ - inline ~unique_ptr() - { - ContainerDeletePolicy ::destroy (object); - } - - /** Changes this unique_ptr to point to a new object. - - Because a pointer can only belong to one unique_ptr, this transfers - the pointer from the other object to this one, and the other object is reset to - be a null pointer. - - If this unique_ptr already points to an object, that object - will first be deleted. - */ - unique_ptr& operator= (unique_ptr& objectToTransferFrom) - { - if (this != objectToTransferFrom.getAddress()) - { - // Two ScopedPointers should never be able to refer to the same object - if - // this happens, you must have done something dodgy! - bassert (object == nullptr || object != objectToTransferFrom.object); - - ObjectType* const oldObject = object; - object = objectToTransferFrom.object; - objectToTransferFrom.object = nullptr; - ContainerDeletePolicy ::destroy (oldObject); - } - - return *this; - } - - /** Changes this unique_ptr to point to a new object. - - If this unique_ptr already points to an object, that object - will first be deleted. - - The pointer that you pass in may be a nullptr. - */ - unique_ptr& operator= (ObjectType* const newObjectToTakePossessionOf) - { - if (object != newObjectToTakePossessionOf) - { - ObjectType* const oldObject = object; - object = newObjectToTakePossessionOf; - ContainerDeletePolicy ::destroy (oldObject); - } - - return *this; - } - - #if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS - unique_ptr (unique_ptr&& other) - : object (other.object) - { - other.object = nullptr; - } - - unique_ptr& operator= (unique_ptr&& other) - { - object = other.object; - other.object = nullptr; - return *this; - } - #endif - - //============================================================================== - /** Returns the object that this unique_ptr refers to. */ - inline operator ObjectType*() const { return object; } - - /** Returns the object that this unique_ptr refers to. */ - inline ObjectType* get() const { return object; } - - /** Returns the object that this unique_ptr refers to. */ - inline ObjectType& operator*() const { return *object; } - - /** Lets you access methods and properties of the object that this unique_ptr refers to. */ - inline ObjectType* operator->() const { return object; } - - //============================================================================== - /** Removes the current object from this unique_ptr without deleting it. - This will return the current object, and set the unique_ptr to a null pointer. - */ - ObjectType* release() { ObjectType* const o = object; object = nullptr; return o; } - - //============================================================================== - /** Swaps this object with that of another unique_ptr. - The two objects simply exchange their pointers. - */ - void swapWith (unique_ptr & other) - { - // Two ScopedPointers should never be able to refer to the same object - if - // this happens, you must have done something dodgy! - bassert (object != other.object || this == other.getAddress()); - std::swap (object, other.object); - } - - inline ObjectType* createCopy() const { return createCopyIfNotNull (object); } - -private: - ObjectType* object; - const unique_ptr* getAddress() const { return this; } -}; - -template -bool operator== (const unique_ptr& pointer1, ObjectType* const pointer2) -{ - return static_cast (pointer1) == pointer2; -} - -template -bool operator!= (const unique_ptr& pointer1, ObjectType* const pointer2) -{ - return static_cast (pointer1) != pointer2; -} - -//------------------------------------------------------------------------------ - -} - -#endif - -namespace beast { - -template -unique_ptr make_unique () -{ - return unique_ptr (new T ()); -} - -template -unique_ptr make_unique (P1 p1) -{ - return unique_ptr (new T (p1)); -} - -template -unique_ptr make_unique (P1 p1, P2 p2) -{ - return unique_ptr (new T (p1, p2)); -} - -template -unique_ptr make_unique (P1 p1, P2 p2, P3 p3) -{ - return unique_ptr (new T (p1, p2, p3)); -} - -template -unique_ptr make_unique (P1 p1, P2 p2, P3 p3, P4 p4) -{ - return unique_ptr (new T (p1, p2, p3, p4)); -} - -template -unique_ptr make_unique (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) -{ - return unique_ptr (new T (p1, p2, p3, p4, p5)); -} - -template -unique_ptr make_unique (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) -{ - return unique_ptr (new T (p1, p2, p3, p4, p5, p6)); -} - -template -unique_ptr make_unique (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) -{ - return unique_ptr (new T (p1, p2, p3, p4, p5, p6, p7)); -} - -template -unique_ptr make_unique (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) -{ - return unique_ptr (new T (p1, p2, p3, p4, p5, p6, p7, p8)); -} - -} - -#endif diff --git a/src/beast/beast/threads/ServiceQueue.h b/src/beast/beast/threads/ServiceQueue.h index 8ccd974cb0..2489d5171c 100644 --- a/src/beast/beast/threads/ServiceQueue.h +++ b/src/beast/beast/threads/ServiceQueue.h @@ -22,7 +22,6 @@ #include "../chrono/CPUMeter.h" #include "../intrusive/List.h" -#include "../intrusive/LockFreeStack.h" #include "SharedData.h" #include "ThreadLocalValue.h" #include "WaitableEvent.h" @@ -371,7 +370,7 @@ protected: //-------------------------------------------------------------------------- - class Waiter : public LockFreeStack ::Node + class Waiter : public List ::Node { public: Waiter() @@ -390,8 +389,8 @@ protected: { // handlers List handlers; - LockFreeStack waiting; - LockFreeStack unused; + List waiting; + List unused; }; typedef SharedData SharedState; @@ -440,9 +439,8 @@ public: typename Allocator::template rebind ::other a (m_alloc); SharedState::Access state (m_state); while (expectedConcurrency--) - { - state->unused.push_front (new (a.allocate (1)) Waiter); - } + state->unused.push_front ( + *new (a.allocate (1)) Waiter); } ~ServiceQueueType() @@ -456,11 +454,10 @@ public: bassert (state->waiting.empty()); typename Allocator::template rebind ::other a (m_alloc); - for(;;) + while (! state->unused.empty ()) { - Waiter* const waiter (state->unused.pop_front()); - if (waiter == nullptr) - break; + Waiter* const waiter (&state->unused.front ()); + state->unused.pop_front (); a.destroy (waiter); a.deallocate (waiter, 1); } diff --git a/src/beast/beast/threads/impl/ServiceQueue.cpp b/src/beast/beast/threads/impl/ServiceQueue.cpp index 16aaddb74d..7f62cc3cb3 100644 --- a/src/beast/beast/threads/impl/ServiceQueue.cpp +++ b/src/beast/beast/threads/impl/ServiceQueue.cpp @@ -119,12 +119,11 @@ void ServiceQueueBase::stop () { SharedState::Access state (m_state); m_stopped.set (1); - for(;;) + while (! state->waiting.empty ()) { - Waiter* waiting (state->waiting.pop_front()); - if (waiting == nullptr) - break; - waiting->signal(); + Waiter& waiting (state->waiting.front()); + state->waiting.pop_front (); + waiting.signal (); } } @@ -144,14 +143,24 @@ void ServiceQueueBase::wait () { SharedState::Access state (m_state); + if (stopped ()) return; + if (! state->handlers.empty()) return; - waiter = state->unused.pop_front(); - if (! waiter) + + if (state->unused.empty ()) + { waiter = new_waiter(); - state->waiting.push_front (waiter); + } + else + { + waiter = &state->unused.front (); + state->unused.pop_front (); + } + + state->waiting.push_front (*waiter); } waiter->wait(); @@ -160,19 +169,22 @@ void ServiceQueueBase::wait () { SharedState::Access state (m_state); - state->unused.push_front (waiter); + state->unused.push_front (*waiter); } } void ServiceQueueBase::enqueue (Item* item) { - Waiter* waiter; + Waiter* waiter (nullptr); { SharedState::Access state (m_state); state->handlers.push_back (*item); - // Signal a Waiter if one exists - waiter = state->waiting.pop_front(); + if (! state->waiting.empty ()) + { + waiter = &state->waiting.front (); + state->waiting.pop_front (); + } } if (waiter != nullptr) diff --git a/src/beast/beast/threads/semaphore.h b/src/beast/beast/threads/semaphore.h new file mode 100644 index 0000000000..096a057446 --- /dev/null +++ b/src/beast/beast/threads/semaphore.h @@ -0,0 +1,86 @@ +//------------------------------------------------------------------------------ +/* + This file is part of Beast: https://github.com/vinniefalco/Beast + Copyright 2013, Vinnie Falco + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ +//============================================================================== + +#ifndef BEAST_THREADS_SEMAPHORE_H_INCLUDED +#define BEAST_THREADS_SEMAPHORE_H_INCLUDED + +#include +#include + +namespace beast { + +template +class basic_semaphore +{ +private: + typedef std::unique_lock scoped_lock; + + Mutex m_mutex; + CondVar m_cond; + std::size_t m_count; + +public: + typedef std::size_t size_type; + + /** Create the semaphore, with an optional initial count. + If unspecified, the initial count is zero. + */ + explicit basic_semaphore (size_type count = 0) + : m_count (count) + { + } + + /** Increment the count and unblock one waiting thread. */ + void notify () + { + scoped_lock lock (m_mutex); + ++m_count; + m_cond.notify_one (); + } + + // Deprecated, for backward compatibility + void signal () { notify (); } + + /** Block until notify is called. */ + void wait () + { + scoped_lock lock (m_mutex); + while (m_count == 0) + m_cond.wait (lock); + --m_count; + } + + /** Perform a non-blocking wait. + @return `true` If the wait would be satisfied. + */ + bool try_wait () + { + scoped_lock lock (m_mutex); + if (m_count == 0) + return false; + --m_count; + return true; + } +}; + +typedef basic_semaphore semaphore; +} + +#endif + diff --git a/src/beast/modules/beast_asio/async/SharedHandlerAllocator.h b/src/beast/modules/beast_asio/async/SharedHandlerAllocator.h index 0c61b8b668..787beebbff 100644 --- a/src/beast/modules/beast_asio/async/SharedHandlerAllocator.h +++ b/src/beast/modules/beast_asio/async/SharedHandlerAllocator.h @@ -24,7 +24,7 @@ This class is compatible with std::allocator and can be used in any boost interface which takes a template parameter of type Allocator. - This includes boost::function and especially boost::asio::streambuf + This includes std::function and especially boost::asio::streambuf and relatives. This is vastly more efficient in a variety of situations especially during an upcall and when using stackful coroutines. diff --git a/src/beast/modules/beast_core/beast_core.cpp b/src/beast/modules/beast_core/beast_core.cpp index 1b6761e3d6..2bcd1f08ef 100644 --- a/src/beast/modules/beast_core/beast_core.cpp +++ b/src/beast/modules/beast_core/beast_core.cpp @@ -129,7 +129,6 @@ namespace beast { -#include "containers/AbstractFifo.cpp" #include "containers/DynamicObject.cpp" #include "containers/NamedValueSet.cpp" #include "containers/PropertySet.cpp" @@ -155,7 +154,6 @@ namespace beast #include "logging/Logger.cpp" #include "maths/BigInteger.cpp" -#include "maths/Expression.cpp" #include "maths/Random.cpp" #include "memory/MemoryBlock.cpp" @@ -188,7 +186,6 @@ namespace beast #include "thread/impl/TrackedMutex.cpp" #include "thread/DeadlineTimer.cpp" -#include "thread/Semaphore.cpp" #include "thread/Workers.cpp" #include "threads/ChildProcess.cpp" diff --git a/src/beast/modules/beast_core/beast_core.h b/src/beast/modules/beast_core/beast_core.h index 911825d976..c3526cf918 100644 --- a/src/beast/modules/beast_core/beast_core.h +++ b/src/beast/modules/beast_core/beast_core.h @@ -77,10 +77,6 @@ class FileOutputStream; #include "diagnostic/Throw.h" #include "system/Functional.h" -#include "memory/AtomicCounter.h" -#include "memory/AtomicFlag.h" -#include "memory/AtomicPointer.h" -#include "memory/AtomicState.h" #include "threads/SpinDelay.h" #include "time/AtExitHook.h" @@ -155,7 +151,6 @@ class FileOutputStream; #include "logging/Logger.h" #include "diagnostic/FPUFlags.h" #include "memory/SharedFunction.h" -#include "containers/AbstractFifo.h" #include "text/Identifier.h" #include "containers/Variant.h" #include "containers/LinkedListPointer.h" @@ -163,13 +158,10 @@ class FileOutputStream; #include "containers/DynamicObject.h" #include "maths/BigInteger.h" #include "maths/Random.h" -#include "containers/LockFreeQueue.h" #include "containers/OwnedArray.h" #include "text/StringPairArray.h" #include "containers/PropertySet.h" -#include "containers/SharedObjectArray.h" #include "containers/ScopedValueSetter.h" -#include "containers/SortedSet.h" #include "maths/Range.h" #include "containers/SparseSet.h" #include "files/DirectoryIterator.h" @@ -186,12 +178,8 @@ class FileOutputStream; #include "json/JSON.h" #include "logging/FileLogger.h" #include "logging/Logger.h" -#include "maths/Expression.h" -#include "maths/Interval.h" #include "memory/OptionalScopedPointer.h" #include "memory/SharedSingleton.h" -#include "memory/WeakReference.h" -#include "memory/RecycledObjectPool.h" #include "misc/Main.h" #include "misc/Uuid.h" #include "misc/WindowsRegistry.h" @@ -228,7 +216,6 @@ class FileOutputStream; #include "thread/DeadlineTimer.h" -#include "thread/Semaphore.h" #include "thread/Workers.h" } diff --git a/src/beast/modules/beast_core/containers/AbstractFifo.cpp b/src/beast/modules/beast_core/containers/AbstractFifo.cpp deleted file mode 100644 index d86fb3291d..0000000000 --- a/src/beast/modules/beast_core/containers/AbstractFifo.cpp +++ /dev/null @@ -1,228 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Portions of this file are from JUCE. - Copyright (c) 2013 - Raw Material Software Ltd. - Please visit http://www.juce.com - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -AbstractFifo::AbstractFifo (const int capacity) noexcept - : bufferSize (capacity) -{ - bassert (bufferSize > 0); -} - -AbstractFifo::~AbstractFifo() {} - -int AbstractFifo::getTotalSize() const noexcept { return bufferSize; } -int AbstractFifo::getFreeSpace() const noexcept { return bufferSize - getNumReady(); } - -int AbstractFifo::getNumReady() const noexcept -{ - const int vs = validStart.get(); - const int ve = validEnd.get(); - return ve >= vs ? (ve - vs) : (bufferSize - (vs - ve)); -} - -void AbstractFifo::reset() noexcept -{ - validEnd = 0; - validStart = 0; -} - -void AbstractFifo::setTotalSize (int newSize) noexcept -{ - bassert (newSize > 0); - reset(); - bufferSize = newSize; -} - -//============================================================================== -void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept -{ - const int vs = validStart.get(); - const int ve = validEnd.value; - - const int freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve); - numToWrite = bmin (numToWrite, freeSpace - 1); - - if (numToWrite <= 0) - { - startIndex1 = 0; - startIndex2 = 0; - blockSize1 = 0; - blockSize2 = 0; - } - else - { - startIndex1 = ve; - startIndex2 = 0; - blockSize1 = bmin (bufferSize - ve, numToWrite); - numToWrite -= blockSize1; - blockSize2 = numToWrite <= 0 ? 0 : bmin (numToWrite, vs); - } -} - -void AbstractFifo::finishedWrite (int numWritten) noexcept -{ - bassert (numWritten >= 0 && numWritten < bufferSize); - int newEnd = validEnd.value + numWritten; - if (newEnd >= bufferSize) - newEnd -= bufferSize; - - validEnd = newEnd; -} - -void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept -{ - const int vs = validStart.value; - const int ve = validEnd.get(); - - const int numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve)); - numWanted = bmin (numWanted, numReady); - - if (numWanted <= 0) - { - startIndex1 = 0; - startIndex2 = 0; - blockSize1 = 0; - blockSize2 = 0; - } - else - { - startIndex1 = vs; - startIndex2 = 0; - blockSize1 = bmin (bufferSize - vs, numWanted); - numWanted -= blockSize1; - blockSize2 = numWanted <= 0 ? 0 : bmin (numWanted, ve); - } -} - -void AbstractFifo::finishedRead (int numRead) noexcept -{ - bassert (numRead >= 0 && numRead <= bufferSize); - - int newStart = validStart.value + numRead; - if (newStart >= bufferSize) - newStart -= bufferSize; - - validStart = newStart; -} - -//============================================================================== - -class AbstractFifoTests : public UnitTest -{ -public: - AbstractFifoTests() : UnitTest ("Abstract Fifo", "beast") - { - } - - class WriteThread : public Thread - { - public: - WriteThread (AbstractFifo& fifo_, int* buffer_) - : Thread ("fifo writer"), fifo (fifo_), buffer (buffer_) - { - startThread(); - } - - ~WriteThread() - { - stopThread (5000); - } - - void run() - { - int n = 0; - Random r; - - while (! threadShouldExit()) - { - int num = r.nextInt (2000) + 1; - - int start1, size1, start2, size2; - fifo.prepareToWrite (num, start1, size1, start2, size2); - - bassert (size1 >= 0 && size2 >= 0); - bassert (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize())); - bassert (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize())); - - for (int i = 0; i < size1; ++i) - buffer [start1 + i] = n++; - - for (int i = 0; i < size2; ++i) - buffer [start2 + i] = n++; - - fifo.finishedWrite (size1 + size2); - } - } - - private: - AbstractFifo& fifo; - int* buffer; - }; - - void runTest() - { - beginTestCase ("AbstractFifo"); - - int buffer [5000]; - AbstractFifo fifo (numElementsInArray (buffer)); - - WriteThread writer (fifo, buffer); - - int n = 0; - Random r; - - bool failed = false; - - for (int count = 100000; --count >= 0;) - { - int num = r.nextInt (6000) + 1; - - int start1, size1, start2, size2; - fifo.prepareToRead (num, start1, size1, start2, size2); - - if (! (size1 >= 0 && size2 >= 0) - && (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize())) - && (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()))) - { - expect (false, "prepareToRead returned negative values"); - break; - } - - for (int i = 0; i < size1; ++i) - failed = (buffer [start1 + i] != n++) || failed; - - for (int i = 0; i < size2; ++i) - failed = (buffer [start2 + i] != n++) || failed; - - if (failed) - { - break; - } - - fifo.finishedRead (size1 + size2); - } - - expect (! failed, "read values were incorrect"); - } -}; - -static AbstractFifoTests abstractFifoTests; diff --git a/src/beast/modules/beast_core/containers/AbstractFifo.h b/src/beast/modules/beast_core/containers/AbstractFifo.h deleted file mode 100644 index f7196a1a38..0000000000 --- a/src/beast/modules/beast_core/containers/AbstractFifo.h +++ /dev/null @@ -1,212 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Portions of this file are from JUCE. - Copyright (c) 2013 - Raw Material Software Ltd. - Please visit http://www.juce.com - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ABSTRACTFIFO_H_INCLUDED -#define BEAST_ABSTRACTFIFO_H_INCLUDED - -//============================================================================== -/** - Encapsulates the logic required to implement a lock-free FIFO. - - This class handles the logic needed when building a single-reader, - single-writer FIFO. - - It doesn't actually hold any data itself, but your FIFO class can use one of - these to manage its position and status when reading or writing to it. - - To use it, you can call prepareToWrite() to determine the position within - your own buffer that an incoming block of data should be stored, and - prepareToRead() to find out when the next outgoing block should be read from. - - e.g. - @code - class MyFifo - { - public: - MyFifo() : abstractFifo (1024) - { - } - - void addToFifo (const int* someData, int numItems) - { - int start1, size1, start2, size2; - abstractFifo.prepareToWrite (numItems, start1, size1, start2, size2); - - if (size1 > 0) - copySomeData (myBuffer + start1, someData, size1); - - if (size2 > 0) - copySomeData (myBuffer + start2, someData + size1, size2); - - abstractFifo.finishedWrite (size1 + size2); - } - - void readFromFifo (int* someData, int numItems) - { - int start1, size1, start2, size2; - abstractFifo.prepareToRead (numSamples, start1, size1, start2, size2); - - if (size1 > 0) - copySomeData (someData, myBuffer + start1, size1); - - if (size2 > 0) - copySomeData (someData + size1, myBuffer + start2, size2); - - abstractFifo.finishedRead (size1 + size2); - } - - private: - AbstractFifo abstractFifo; - int myBuffer [1024]; - }; - @endcode -*/ -class BEAST_API AbstractFifo : LeakChecked , public Uncopyable -{ -public: - //============================================================================== - /** Creates a FIFO to manage a buffer with the specified capacity. */ - AbstractFifo (int capacity) noexcept; - - /** Destructor */ - ~AbstractFifo(); - - //============================================================================== - /** Returns the total size of the buffer being managed. */ - int getTotalSize() const noexcept; - - /** Returns the number of items that can currently be added to the buffer without it overflowing. */ - int getFreeSpace() const noexcept; - - /** Returns the number of items that can currently be read from the buffer. */ - int getNumReady() const noexcept; - - /** Clears the buffer positions, so that it appears empty. */ - void reset() noexcept; - - /** Changes the buffer's total size. - Note that this isn't thread-safe, so don't call it if there's any danger that it - might overlap with a call to any other method in this class! - */ - void setTotalSize (int newSize) noexcept; - - //============================================================================== - /** Returns the location within the buffer at which an incoming block of data should be written. - - Because the section of data that you want to add to the buffer may overlap the end - and wrap around to the start, two blocks within your buffer are returned, and you - should copy your data into the first one, with any remaining data spilling over into - the second. - - If the number of items you ask for is too large to fit within the buffer's free space, then - blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you - may decide to keep waiting and re-trying the method until there's enough space available. - - After calling this method, if you choose to write your data into the blocks returned, you - must call finishedWrite() to tell the FIFO how much data you actually added. - - e.g. - @code - void addToFifo (const int* someData, int numItems) - { - int start1, size1, start2, size2; - prepareToWrite (numItems, start1, size1, start2, size2); - - if (size1 > 0) - copySomeData (myBuffer + start1, someData, size1); - - if (size2 > 0) - copySomeData (myBuffer + start2, someData + size1, size2); - - finishedWrite (size1 + size2); - } - @endcode - - @param numToWrite indicates how many items you'd like to add to the buffer - @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written - @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1 - @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into - the first block should be written - @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2 - @see finishedWrite - */ - void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept; - - /** Called after writing from the FIFO, to indicate that this many items have been added. - @see prepareToWrite - */ - void finishedWrite (int numWritten) noexcept; - - /** Returns the location within the buffer from which the next block of data should be read. - - Because the section of data that you want to read from the buffer may overlap the end - and wrap around to the start, two blocks within your buffer are returned, and you - should read from both of them. - - If the number of items you ask for is greater than the amount of data available, then - blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you - may decide to keep waiting and re-trying the method until there's enough data available. - - After calling this method, if you choose to read the data, you must call finishedRead() to - tell the FIFO how much data you have consumed. - - e.g. - @code - void readFromFifo (int* someData, int numItems) - { - int start1, size1, start2, size2; - prepareToRead (numSamples, start1, size1, start2, size2); - - if (size1 > 0) - copySomeData (someData, myBuffer + start1, size1); - - if (size2 > 0) - copySomeData (someData + size1, myBuffer + start2, size2); - - finishedRead (size1 + size2); - } - @endcode - - @param numWanted indicates how many items you'd like to add to the buffer - @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written - @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1 - @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into - the first block should be written - @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2 - @see finishedRead - */ - void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept; - - /** Called after reading from the FIFO, to indicate that this many items have now been consumed. - @see prepareToRead - */ - void finishedRead (int numRead) noexcept; - -private: - //============================================================================== - int bufferSize; - Atomic validStart, validEnd; -}; - -#endif - diff --git a/src/beast/modules/beast_core/containers/SharedObjectArray.h b/src/beast/modules/beast_core/containers/SharedObjectArray.h deleted file mode 100644 index d2205c17d4..0000000000 --- a/src/beast/modules/beast_core/containers/SharedObjectArray.h +++ /dev/null @@ -1,856 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Portions of this file are from JUCE. - Copyright (c) 2013 - Raw Material Software Ltd. - Please visit http://www.juce.com - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_SHAREDOBJECTARRAY_H_INCLUDED -#define BEAST_SHAREDOBJECTARRAY_H_INCLUDED - -//============================================================================== -/** - Holds a list of objects derived from SharedObject. - - A SharedObjectArray holds objects derived from SharedObject, - and takes care of incrementing and decrementing their ref counts when they - are added and removed from the array. - - To make all the array's methods thread-safe, pass in "CriticalSection" as the templated - TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection. - - @see Array, OwnedArray, StringArray -*/ -template -class SharedObjectArray -{ -public: - typedef SharedPtr ObjectClassPtr; - - //============================================================================== - /** Creates an empty array. - @see SharedObject, Array, OwnedArray - */ - SharedObjectArray() noexcept - : numUsed (0) - { - } - - /** Creates a copy of another array */ - SharedObjectArray (const SharedObjectArray& other) noexcept - { - const ScopedLockType lock (other.getLock()); - numUsed = other.size(); - data.setAllocatedSize (numUsed); - memcpy (data.elements, other.getRawDataPointer(), numUsed * sizeof (ObjectClass*)); - - for (int i = numUsed; --i >= 0;) - if (ObjectClass* o = data.elements[i]) - o->incReferenceCount(); - } - - /** Creates a copy of another array */ - template - SharedObjectArray (const SharedObjectArray& other) noexcept - { - const typename SharedObjectArray::ScopedLockType lock (other.getLock()); - numUsed = other.size(); - data.setAllocatedSize (numUsed); - memcpy (data.elements, other.getRawDataPointer(), numUsed * sizeof (ObjectClass*)); - - for (int i = numUsed; --i >= 0;) - if (ObjectClass* o = data.elements[i]) - o->incReferenceCount(); - } - - /** Copies another array into this one. - Any existing objects in this array will first be released. - */ - SharedObjectArray& operator= (const SharedObjectArray& other) noexcept - { - SharedObjectArray otherCopy (other); - swapWith (otherCopy); - return *this; - } - - /** Copies another array into this one. - Any existing objects in this array will first be released. - */ - template - SharedObjectArray& operator= (const SharedObjectArray& other) noexcept - { - SharedObjectArray otherCopy (other); - swapWith (otherCopy); - return *this; - } - - /** Destructor. - Any objects in the array will be released, and may be deleted if not referenced from elsewhere. - */ - ~SharedObjectArray() - { - clear(); - } - - //============================================================================== - /** Removes all objects from the array. - - Any objects in the array that are not referenced from elsewhere will be deleted. - */ - void clear() - { - const ScopedLockType lock (getLock()); - - while (numUsed > 0) - if (ObjectClass* o = data.elements [--numUsed]) - o->decReferenceCount(); - - bassert (numUsed == 0); - data.setAllocatedSize (0); - } - - /** Returns the current number of objects in the array. */ - inline int size() const noexcept - { - return numUsed; - } - - /** Returns a pointer to the object at this index in the array. - - If the index is out-of-range, this will return a null pointer, (and - it could be null anyway, because it's ok for the array to hold null - pointers as well as objects). - - @see getUnchecked - */ - inline ObjectClassPtr operator[] (const int index) const noexcept - { - return getObjectPointer (index); - } - - /** Returns a pointer to the object at this index in the array, without checking - whether the index is in-range. - - This is a faster and less safe version of operator[] which doesn't check the index passed in, so - it can be used when you're sure the index is always going to be legal. - */ - inline ObjectClassPtr getUnchecked (const int index) const noexcept - { - return getObjectPointerUnchecked (index); - } - - /** Returns a raw pointer to the object at this index in the array. - - If the index is out-of-range, this will return a null pointer, (and - it could be null anyway, because it's ok for the array to hold null - pointers as well as objects). - - @see getUnchecked - */ - inline ObjectClass* getObjectPointer (const int index) const noexcept - { - const ScopedLockType lock (getLock()); - return isPositiveAndBelow (index, numUsed) ? data.elements [index] - : nullptr; - } - - /** Returns a raw pointer to the object at this index in the array, without checking - whether the index is in-range. - */ - inline ObjectClass* getObjectPointerUnchecked (const int index) const noexcept - { - const ScopedLockType lock (getLock()); - bassert (isPositiveAndBelow (index, numUsed)); - return data.elements [index]; - } - - /** Returns a pointer to the first object in the array. - - This will return a null pointer if the array's empty. - @see getLast - */ - inline ObjectClassPtr getFirst() const noexcept - { - const ScopedLockType lock (getLock()); - return numUsed > 0 ? data.elements [0] - : static_cast (nullptr); - } - - /** Returns a pointer to the last object in the array. - - This will return a null pointer if the array's empty. - @see getFirst - */ - inline ObjectClassPtr getLast() const noexcept - { - const ScopedLockType lock (getLock()); - return numUsed > 0 ? data.elements [numUsed - 1] - : static_cast (nullptr); - } - - /** Returns a pointer to the actual array data. - This pointer will only be valid until the next time a non-const method - is called on the array. - */ - inline ObjectClass** getRawDataPointer() const noexcept - { - return data.elements; - } - - //============================================================================== - /** Returns a pointer to the first element in the array. - This method is provided for compatibility with standard C++ iteration mechanisms. - */ - inline ObjectClass** begin() const noexcept - { - return data.elements; - } - - /** Returns a pointer to the element which follows the last element in the array. - This method is provided for compatibility with standard C++ iteration mechanisms. - */ - inline ObjectClass** end() const noexcept - { - return data.elements + numUsed; - } - - //============================================================================== - /** Finds the index of the first occurrence of an object in the array. - - @param objectToLookFor the object to look for - @returns the index at which the object was found, or -1 if it's not found - */ - int indexOf (const ObjectClass* const objectToLookFor) const noexcept - { - const ScopedLockType lock (getLock()); - ObjectClass** e = data.elements.getData(); - ObjectClass** const endPointer = e + numUsed; - - while (e != endPointer) - { - if (objectToLookFor == *e) - return static_cast (e - data.elements.getData()); - - ++e; - } - - return -1; - } - - /** Returns true if the array contains a specified object. - - @param objectToLookFor the object to look for - @returns true if the object is in the array - */ - bool contains (const ObjectClass* const objectToLookFor) const noexcept - { - const ScopedLockType lock (getLock()); - ObjectClass** e = data.elements.getData(); - ObjectClass** const endPointer = e + numUsed; - - while (e != endPointer) - { - if (objectToLookFor == *e) - return true; - - ++e; - } - - return false; - } - - /** Appends a new object to the end of the array. - - This will increase the new object's reference count. - - @param newObject the new object to add to the array - @see set, insert, addIfNotAlreadyThere, addSorted, addArray - */ - ObjectClass* add (ObjectClass* const newObject) noexcept - { - const ScopedLockType lock (getLock()); - data.ensureAllocatedSize (numUsed + 1); - bassert (data.elements != nullptr); - data.elements [numUsed++] = newObject; - - if (newObject != nullptr) - newObject->incReferenceCount(); - - return newObject; - } - - /** Inserts a new object into the array at the given index. - - If the index is less than 0 or greater than the size of the array, the - element will be added to the end of the array. - Otherwise, it will be inserted into the array, moving all the later elements - along to make room. - - This will increase the new object's reference count. - - @param indexToInsertAt the index at which the new element should be inserted - @param newObject the new object to add to the array - @see add, addSorted, addIfNotAlreadyThere, set - */ - ObjectClass* insert (int indexToInsertAt, - ObjectClass* const newObject) noexcept - { - if (indexToInsertAt >= 0) - { - const ScopedLockType lock (getLock()); - - if (indexToInsertAt > numUsed) - indexToInsertAt = numUsed; - - data.ensureAllocatedSize (numUsed + 1); - bassert (data.elements != nullptr); - - ObjectClass** const e = data.elements + indexToInsertAt; - const int numToMove = numUsed - indexToInsertAt; - - if (numToMove > 0) - memmove (e + 1, e, sizeof (ObjectClass*) * (size_t) numToMove); - - *e = newObject; - - if (newObject != nullptr) - newObject->incReferenceCount(); - - ++numUsed; - - return newObject; - } - else - { - return add (newObject); - } - } - - /** Appends a new object at the end of the array as long as the array doesn't - already contain it. - - If the array already contains a matching object, nothing will be done. - - @param newObject the new object to add to the array - */ - void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept - { - const ScopedLockType lock (getLock()); - if (! contains (newObject)) - add (newObject); - } - - /** Replaces an object in the array with a different one. - - If the index is less than zero, this method does nothing. - If the index is beyond the end of the array, the new object is added to the end of the array. - - The object being added has its reference count increased, and if it's replacing - another object, then that one has its reference count decreased, and may be deleted. - - @param indexToChange the index whose value you want to change - @param newObject the new value to set for this index. - @see add, insert, remove - */ - void set (const int indexToChange, - ObjectClass* const newObject) - { - if (indexToChange >= 0) - { - const ScopedLockType lock (getLock()); - - if (newObject != nullptr) - newObject->incReferenceCount(); - - if (indexToChange < numUsed) - { - if (ObjectClass* o = data.elements [indexToChange]) - o->decReferenceCount(); - - data.elements [indexToChange] = newObject; - } - else - { - data.ensureAllocatedSize (numUsed + 1); - bassert (data.elements != nullptr); - data.elements [numUsed++] = newObject; - } - } - } - - /** Adds elements from another array to the end of this array. - - @param arrayToAddFrom the array from which to copy the elements - @param startIndex the first element of the other array to start copying from - @param numElementsToAdd how many elements to add from the other array. If this - value is negative or greater than the number of available elements, - all available elements will be copied. - @see add - */ - void addArray (const SharedObjectArray& arrayToAddFrom, - int startIndex = 0, - int numElementsToAdd = -1) noexcept - { - const ScopedLockType lock1 (arrayToAddFrom.getLock()); - - { - const ScopedLockType lock2 (getLock()); - - if (startIndex < 0) - { - bassertfalse; - startIndex = 0; - } - - if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size()) - numElementsToAdd = arrayToAddFrom.size() - startIndex; - - if (numElementsToAdd > 0) - { - data.ensureAllocatedSize (numUsed + numElementsToAdd); - - while (--numElementsToAdd >= 0) - add (arrayToAddFrom.getUnchecked (startIndex++)); - } - } - } - - /** Inserts a new object into the array assuming that the array is sorted. - - This will use a comparator to find the position at which the new object - should go. If the array isn't sorted, the behaviour of this - method will be unpredictable. - - @param comparator the comparator object to use to compare the elements - see the - sort() method for details about this object's form - @param newObject the new object to insert to the array - @returns the index at which the new object was added - @see add, sort - */ - template - int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept - { - const ScopedLockType lock (getLock()); - const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed); - insert (index, newObject); - return index; - } - - /** Inserts or replaces an object in the array, assuming it is sorted. - - This is similar to addSorted, but if a matching element already exists, then it will be - replaced by the new one, rather than the new one being added as well. - */ - template - void addOrReplaceSorted (ElementComparator& comparator, - ObjectClass* newObject) noexcept - { - const ScopedLockType lock (getLock()); - const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed); - - if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0) - set (index - 1, newObject); // replace an existing object that matches - else - insert (index, newObject); // no match, so insert the new one - } - - /** Finds the index of an object in the array, assuming that the array is sorted. - - This will use a comparator to do a binary-chop to find the index of the given - element, if it exists. If the array isn't sorted, the behaviour of this - method will be unpredictable. - - @param comparator the comparator to use to compare the elements - see the sort() - method for details about the form this object should take - @param objectToLookFor the object to search for - @returns the index of the element, or -1 if it's not found - @see addSorted, sort - */ - template - int indexOfSorted (ElementComparator& comparator, - const ObjectClass* const objectToLookFor) const noexcept - { - (void) comparator; - const ScopedLockType lock (getLock()); - int s = 0, e = numUsed; - - while (s < e) - { - if (comparator.compareElements (objectToLookFor, data.elements [s]) == 0) - return s; - - const int halfway = (s + e) / 2; - if (halfway == s) - break; - - if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0) - s = halfway; - else - e = halfway; - } - - return -1; - } - - //============================================================================== - /** Removes an object from the array. - - This will remove the object at a given index and move back all the - subsequent objects to close the gap. - - If the index passed in is out-of-range, nothing will happen. - - The object that is removed will have its reference count decreased, - and may be deleted if not referenced from elsewhere. - - @param indexToRemove the index of the element to remove - @see removeObject, removeRange - */ - void remove (const int indexToRemove) - { - const ScopedLockType lock (getLock()); - - if (isPositiveAndBelow (indexToRemove, numUsed)) - { - ObjectClass** const e = data.elements + indexToRemove; - - if (ObjectClass* o = *e) - o->decReferenceCount(); - - --numUsed; - const int numberToShift = numUsed - indexToRemove; - - if (numberToShift > 0) - memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numberToShift); - - if ((numUsed << 1) < data.numAllocated) - minimiseStorageOverheads(); - } - } - - /** Removes and returns an object from the array. - - This will remove the object at a given index and return it, moving back all - the subsequent objects to close the gap. If the index passed in is out-of-range, - nothing will happen and a null pointer will be returned. - - @param indexToRemove the index of the element to remove - @see remove, removeObject, removeRange - */ - ObjectClassPtr removeAndReturn (const int indexToRemove) - { - ObjectClassPtr removedItem; - const ScopedLockType lock (getLock()); - - if (isPositiveAndBelow (indexToRemove, numUsed)) - { - ObjectClass** const e = data.elements + indexToRemove; - - if (ObjectClass* o = *e) - { - removedItem = o; - o->decReferenceCount(); - } - - --numUsed; - const int numberToShift = numUsed - indexToRemove; - - if (numberToShift > 0) - memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numberToShift); - - if ((numUsed << 1) < data.numAllocated) - minimiseStorageOverheads(); - } - - return removedItem; - } - - /** Removes the first occurrence of a specified object from the array. - - If the item isn't found, no action is taken. If it is found, it is - removed and has its reference count decreased. - - @param objectToRemove the object to try to remove - @see remove, removeRange - */ - void removeObject (ObjectClass* const objectToRemove) - { - const ScopedLockType lock (getLock()); - remove (indexOf (objectToRemove)); - } - - /** Removes a range of objects from the array. - - This will remove a set of objects, starting from the given index, - and move any subsequent elements down to close the gap. - - If the range extends beyond the bounds of the array, it will - be safely clipped to the size of the array. - - The objects that are removed will have their reference counts decreased, - and may be deleted if not referenced from elsewhere. - - @param startIndex the index of the first object to remove - @param numberToRemove how many objects should be removed - @see remove, removeObject - */ - void removeRange (const int startIndex, - const int numberToRemove) - { - const ScopedLockType lock (getLock()); - - const int start = blimit (0, numUsed, startIndex); - const int endIndex = blimit (0, numUsed, startIndex + numberToRemove); - - if (endIndex > start) - { - int i; - for (i = start; i < endIndex; ++i) - { - if (ObjectClass* o = data.elements[i]) - { - o->decReferenceCount(); - data.elements[i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer) - } - } - - const int rangeSize = endIndex - start; - ObjectClass** e = data.elements + start; - i = numUsed - endIndex; - numUsed -= rangeSize; - - while (--i >= 0) - { - *e = e [rangeSize]; - ++e; - } - - if ((numUsed << 1) < data.numAllocated) - minimiseStorageOverheads(); - } - } - - /** Removes the last n objects from the array. - - The objects that are removed will have their reference counts decreased, - and may be deleted if not referenced from elsewhere. - - @param howManyToRemove how many objects to remove from the end of the array - @see remove, removeObject, removeRange - */ - void removeLast (int howManyToRemove = 1) - { - const ScopedLockType lock (getLock()); - - if (howManyToRemove > numUsed) - howManyToRemove = numUsed; - - while (--howManyToRemove >= 0) - remove (numUsed - 1); - } - - /** Swaps a pair of objects in the array. - - If either of the indexes passed in is out-of-range, nothing will happen, - otherwise the two objects at these positions will be exchanged. - */ - void swap (const int index1, - const int index2) noexcept - { - const ScopedLockType lock (getLock()); - - if (isPositiveAndBelow (index1, numUsed) - && isPositiveAndBelow (index2, numUsed)) - { - std::swap (data.elements [index1], - data.elements [index2]); - } - } - - /** Moves one of the objects to a different position. - - This will move the object to a specified index, shuffling along - any intervening elements as required. - - So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling - move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }. - - @param currentIndex the index of the object to be moved. If this isn't a - valid index, then nothing will be done - @param newIndex the index at which you'd like this object to end up. If this - is less than zero, it will be moved to the end of the array - */ - void move (const int currentIndex, - int newIndex) noexcept - { - if (currentIndex != newIndex) - { - const ScopedLockType lock (getLock()); - - if (isPositiveAndBelow (currentIndex, numUsed)) - { - if (! isPositiveAndBelow (newIndex, numUsed)) - newIndex = numUsed - 1; - - ObjectClass* const value = data.elements [currentIndex]; - - if (newIndex > currentIndex) - { - memmove (data.elements + currentIndex, - data.elements + currentIndex + 1, - sizeof (ObjectClass*) * (size_t) (newIndex - currentIndex)); - } - else - { - memmove (data.elements + newIndex + 1, - data.elements + newIndex, - sizeof (ObjectClass*) * (size_t) (currentIndex - newIndex)); - } - - data.elements [newIndex] = value; - } - } - } - - //============================================================================== - /** This swaps the contents of this array with those of another array. - - If you need to exchange two arrays, this is vastly quicker than using copy-by-value - because it just swaps their internal pointers. - */ - template - void swapWith (OtherArrayType& otherArray) noexcept - { - const ScopedLockType lock1 (getLock()); - const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock()); - - data.swapWith (otherArray.data); - std::swap (numUsed, otherArray.numUsed); - } - - //============================================================================== - /** Compares this array to another one. - - @returns true only if the other array contains the same objects in the same order - */ - bool operator== (const SharedObjectArray& other) const noexcept - { - const ScopedLockType lock2 (other.getLock()); - const ScopedLockType lock1 (getLock()); - - if (numUsed != other.numUsed) - return false; - - for (int i = numUsed; --i >= 0;) - if (data.elements [i] != other.data.elements [i]) - return false; - - return true; - } - - /** Compares this array to another one. - - @see operator== - */ - bool operator!= (const SharedObjectArray& other) const noexcept - { - return ! operator== (other); - } - - //============================================================================== - /** Sorts the elements in the array. - - This will use a comparator object to sort the elements into order. The object - passed must have a method of the form: - @code - int compareElements (ElementType first, ElementType second); - @endcode - - ..and this method must return: - - a value of < 0 if the first comes before the second - - a value of 0 if the two objects are equivalent - - a value of > 0 if the second comes before the first - - To improve performance, the compareElements() method can be declared as static or const. - - @param comparator the comparator to use for comparing elements. - @param retainOrderOfEquivalentItems if this is true, then items - which the comparator says are equivalent will be - kept in the order in which they currently appear - in the array. This is slower to perform, but may - be important in some cases. If it's false, a faster - algorithm is used, but equivalent elements may be - rearranged. - - @see sortArray - */ - template - void sort (ElementComparator& comparator, - const bool retainOrderOfEquivalentItems = false) const noexcept - { - (void) comparator; // if you pass in an object with a static compareElements() method, this - // avoids getting warning messages about the parameter being unused - - const ScopedLockType lock (getLock()); - sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems); - } - - //============================================================================== - /** Reduces the amount of storage being used by the array. - - Arrays typically allocate slightly more storage than they need, and after - removing elements, they may have quite a lot of unused space allocated. - This method will reduce the amount of allocated storage to a minimum. - */ - void minimiseStorageOverheads() noexcept - { - const ScopedLockType lock (getLock()); - data.shrinkToNoMoreThan (numUsed); - } - - /** Increases the array's internal storage to hold a minimum number of elements. - - Calling this before adding a large known number of elements means that - the array won't have to keep dynamically resizing itself as the elements - are added, and it'll therefore be more efficient. - */ - void ensureStorageAllocated (const int minNumElements) - { - const ScopedLockType lock (getLock()); - data.ensureAllocatedSize (minNumElements); - } - - //============================================================================== - /** Returns the CriticalSection that locks this array. - To lock, you can call getLock().enter() and getLock().exit(), or preferably use - an object of ScopedLockType as an RAII lock for it. - */ - inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; } - - /** Returns the type of scoped lock to use for locking this array */ - typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType; - -private: - //============================================================================== - ArrayAllocationBase data; - int numUsed; -}; - - -#endif \ No newline at end of file diff --git a/src/beast/modules/beast_core/containers/SortedSet.h b/src/beast/modules/beast_core/containers/SortedSet.h deleted file mode 100644 index d5a96a839c..0000000000 --- a/src/beast/modules/beast_core/containers/SortedSet.h +++ /dev/null @@ -1,492 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Portions of this file are from JUCE. - Copyright (c) 2013 - Raw Material Software Ltd. - Please visit http://www.juce.com - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_SORTEDSET_H_INCLUDED -#define BEAST_SORTEDSET_H_INCLUDED - -#if BEAST_MSVC - #pragma warning (push) - #pragma warning (disable: 4512) -#endif - -//============================================================================== -/** - Holds a set of unique primitive objects, such as ints or doubles. - - A set can only hold one item with a given value, so if for example it's a - set of integers, attempting to add the same integer twice will do nothing - the second time. - - Internally, the list of items is kept sorted (which means that whatever - kind of primitive type is used must support the ==, <, >, <= and >= operators - to determine the order), and searching the set for known values is very fast - because it uses a binary-chop method. - - Note that if you're using a class or struct as the element type, it must be - capable of being copied or moved with a straightforward memcpy, rather than - needing construction and destruction code. - - To make all the set's methods thread-safe, pass in "CriticalSection" as the templated - TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection. - - @see Array, OwnedArray, SharedObjectArray, StringArray, CriticalSection -*/ -template -class SortedSet -{ -public: - //============================================================================== - /** Creates an empty set. */ - SortedSet() noexcept - { - } - - /** Creates a copy of another set. - @param other the set to copy - */ - SortedSet (const SortedSet& other) - : data (other.data) - { - } - - /** Destructor. */ - ~SortedSet() noexcept - { - } - - /** Copies another set over this one. - @param other the set to copy - */ - SortedSet& operator= (const SortedSet& other) noexcept - { - data = other.data; - return *this; - } - - //============================================================================== - /** Compares this set to another one. - Two sets are considered equal if they both contain the same set of elements. - @param other the other set to compare with - */ - bool operator== (const SortedSet& other) const noexcept - { - return data == other.data; - } - - /** Compares this set to another one. - Two sets are considered equal if they both contain the same set of elements. - @param other the other set to compare with - */ - bool operator!= (const SortedSet& other) const noexcept - { - return ! operator== (other); - } - - //============================================================================== - /** Removes all elements from the set. - - This will remove all the elements, and free any storage that the set is - using. To clear it without freeing the storage, use the clearQuick() - method instead. - - @see clearQuick - */ - void clear() noexcept - { - data.clear(); - } - - /** Removes all elements from the set without freeing the array's allocated storage. - - @see clear - */ - void clearQuick() noexcept - { - data.clearQuick(); - } - - //============================================================================== - /** Returns the current number of elements in the set. - */ - inline int size() const noexcept - { - return data.size(); - } - - /** Returns one of the elements in the set. - - If the index passed in is beyond the range of valid elements, this - will return zero. - - If you're certain that the index will always be a valid element, you - can call getUnchecked() instead, which is faster. - - @param index the index of the element being requested (0 is the first element in the set) - @see getUnchecked, getFirst, getLast - */ - inline ElementType operator[] (const int index) const noexcept - { - return data [index]; - } - - /** Returns one of the elements in the set, without checking the index passed in. - Unlike the operator[] method, this will try to return an element without - checking that the index is within the bounds of the set, so should only - be used when you're confident that it will always be a valid index. - - @param index the index of the element being requested (0 is the first element in the set) - @see operator[], getFirst, getLast - */ - inline ElementType getUnchecked (const int index) const noexcept - { - return data.getUnchecked (index); - } - - /** Returns a direct reference to one of the elements in the set, without checking the index passed in. - - This is like getUnchecked, but returns a direct reference to the element, so that - you can alter it directly. Obviously this can be dangerous, so only use it when - absolutely necessary. - - @param index the index of the element being requested (0 is the first element in the array) - */ - inline ElementType& getReference (const int index) const noexcept - { - return data.getReference (index); - } - - /** Returns the first element in the set, or 0 if the set is empty. - - @see operator[], getUnchecked, getLast - */ - inline ElementType getFirst() const noexcept - { - return data.getFirst(); - } - - /** Returns the last element in the set, or 0 if the set is empty. - - @see operator[], getUnchecked, getFirst - */ - inline ElementType getLast() const noexcept - { - return data.getLast(); - } - - //============================================================================== - /** Returns a pointer to the first element in the set. - This method is provided for compatibility with standard C++ iteration mechanisms. - */ - inline ElementType* begin() const noexcept - { - return data.begin(); - } - - /** Returns a pointer to the element which follows the last element in the set. - This method is provided for compatibility with standard C++ iteration mechanisms. - */ - inline ElementType* end() const noexcept - { - return data.end(); - } - - //============================================================================== - /** Finds the index of the first element which matches the value passed in. - - This will search the set for the given object, and return the index - of its first occurrence. If the object isn't found, the method will return -1. - - @param elementToLookFor the value or object to look for - @returns the index of the object, or -1 if it's not found - */ - int indexOf (const ElementType& elementToLookFor) const noexcept - { - const ScopedLockType lock (data.getLock()); - - int s = 0; - int e = data.size(); - - for (;;) - { - if (s >= e) - return -1; - - if (elementToLookFor == data.getReference (s)) - return s; - - const int halfway = (s + e) / 2; - - if (halfway == s) - return -1; - else if (elementToLookFor < data.getReference (halfway)) - e = halfway; - else - s = halfway; - } - } - - /** Returns true if the set contains at least one occurrence of an object. - - @param elementToLookFor the value or object to look for - @returns true if the item is found - */ - bool contains (const ElementType& elementToLookFor) const noexcept - { - return indexOf (elementToLookFor) >= 0; - } - - //============================================================================== - /** Adds a new element to the set, (as long as it's not already in there). - - Note that if a matching element already exists, the new value will be assigned - to the existing one using operator=, so that if there are any differences between - the objects which were not recognised by the object's operator==, then the - set will always contain a copy of the most recently added one. - - @param newElement the new object to add to the set - @returns true if the value was added, or false if it already existed - @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray - */ - bool add (const ElementType& newElement) noexcept - { - const ScopedLockType lock (getLock()); - - int s = 0; - int e = data.size(); - - while (s < e) - { - ElementType& elem = data.getReference (s); - if (newElement == elem) - { - elem = newElement; // force an update in case operator== permits differences. - return false; - } - - const int halfway = (s + e) / 2; - const bool isBeforeHalfway = (newElement < data.getReference (halfway)); - - if (halfway == s) - { - if (! isBeforeHalfway) - ++s; - - break; - } - else if (isBeforeHalfway) - e = halfway; - else - s = halfway; - } - - data.insert (s, newElement); - return true; - } - - /** Adds elements from an array to this set. - - @param elementsToAdd the array of elements to add - @param numElementsToAdd how many elements are in this other array - @see add - */ - void addArray (const ElementType* elementsToAdd, - int numElementsToAdd) noexcept - { - const ScopedLockType lock (getLock()); - - while (--numElementsToAdd >= 0) - add (*elementsToAdd++); - } - - /** Adds elements from another set to this one. - - @param setToAddFrom the set from which to copy the elements - @param startIndex the first element of the other set to start copying from - @param numElementsToAdd how many elements to add from the other set. If this - value is negative or greater than the number of available elements, - all available elements will be copied. - @see add - */ - template - void addSet (const OtherSetType& setToAddFrom, - int startIndex = 0, - int numElementsToAdd = -1) noexcept - { - const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock()); - - { - const ScopedLockType lock2 (getLock()); - bassert (this != &setToAddFrom); - - if (this != &setToAddFrom) - { - if (startIndex < 0) - { - bassertfalse; - startIndex = 0; - } - - if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size()) - numElementsToAdd = setToAddFrom.size() - startIndex; - - if (numElementsToAdd > 0) - addArray (&setToAddFrom.data.getReference (startIndex), numElementsToAdd); - } - } - } - - //============================================================================== - /** Removes an element from the set. - - This will remove the element at a given index. - If the index passed in is out-of-range, nothing will happen. - - @param indexToRemove the index of the element to remove - @returns the element that has been removed - @see removeValue, removeRange - */ - ElementType remove (const int indexToRemove) noexcept - { - return data.remove (indexToRemove); - } - - /** Removes an item from the set. - - This will remove the given element from the set, if it's there. - - @param valueToRemove the object to try to remove - @see remove, removeRange - */ - void removeValue (const ElementType valueToRemove) noexcept - { - const ScopedLockType lock (getLock()); - data.remove (indexOf (valueToRemove)); - } - - /** Removes any elements which are also in another set. - - @param otherSet the other set in which to look for elements to remove - @see removeValuesNotIn, remove, removeValue, removeRange - */ - template - void removeValuesIn (const OtherSetType& otherSet) noexcept - { - const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock()); - const ScopedLockType lock2 (getLock()); - - if (this == &otherSet) - { - clear(); - } - else if (otherSet.size() > 0) - { - for (int i = data.size(); --i >= 0;) - if (otherSet.contains (data.getReference (i))) - remove (i); - } - } - - /** Removes any elements which are not found in another set. - - Only elements which occur in this other set will be retained. - - @param otherSet the set in which to look for elements NOT to remove - @see removeValuesIn, remove, removeValue, removeRange - */ - template - void removeValuesNotIn (const OtherSetType& otherSet) noexcept - { - const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock()); - const ScopedLockType lock2 (getLock()); - - if (this != &otherSet) - { - if (otherSet.size() <= 0) - { - clear(); - } - else - { - for (int i = data.size(); --i >= 0;) - if (! otherSet.contains (data.getReference (i))) - remove (i); - } - } - } - - /** This swaps the contents of this array with those of another array. - - If you need to exchange two arrays, this is vastly quicker than using copy-by-value - because it just swaps their internal pointers. - */ - template - void swapWith (OtherSortedSetType& otherSet) noexcept - { - data.swapWith (otherSet.data); - } - - //============================================================================== - /** Reduces the amount of storage being used by the set. - - Sets typically allocate slightly more storage than they need, and after - removing elements, they may have quite a lot of unused space allocated. - This method will reduce the amount of allocated storage to a minimum. - */ - void minimiseStorageOverheads() noexcept - { - data.minimiseStorageOverheads(); - } - - /** Increases the set's internal storage to hold a minimum number of elements. - - Calling this before adding a large known number of elements means that - the set won't have to keep dynamically resizing itself as the elements - are added, and it'll therefore be more efficient. - */ - void ensureStorageAllocated (const int minNumElements) - { - data.ensureStorageAllocated (minNumElements); - } - - //============================================================================== - /** Returns the CriticalSection that locks this array. - To lock, you can call getLock().enter() and getLock().exit(), or preferably use - an object of ScopedLockType as an RAII lock for it. - */ - inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data.getLock(); } - - /** Returns the type of scoped lock to use for locking this array */ - typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType; - - -private: - //============================================================================== - Array data; -}; - -#if BEAST_MSVC - #pragma warning (pop) -#endif - -#endif - diff --git a/src/beast/modules/beast_core/maths/Expression.cpp b/src/beast/modules/beast_core/maths/Expression.cpp deleted file mode 100644 index c8f780754c..0000000000 --- a/src/beast/modules/beast_core/maths/Expression.cpp +++ /dev/null @@ -1,1162 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Portions of this file are from JUCE. - Copyright (c) 2013 - Raw Material Software Ltd. - Please visit http://www.juce.com - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -class Expression::Term - : public SingleThreadedSharedObject -{ -public: - Term() {} - virtual ~Term() {} - - virtual Type getType() const noexcept = 0; - virtual Term* clone() const = 0; - virtual SharedPtr resolve (const Scope&, int recursionDepth) = 0; - virtual String toString() const = 0; - virtual double toDouble() const { return 0; } - virtual int getInputIndexFor (const Term*) const { return -1; } - virtual int getOperatorPrecedence() const { return 0; } - virtual int getNumInputs() const { return 0; } - virtual Term* getInput (int) const { return nullptr; } - virtual SharedPtr negated(); - - virtual SharedPtr createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/, - double /*overallTarget*/, Term* /*topLevelTerm*/) const - { - bassertfalse; - return SharedPtr(); - } - - virtual String getName() const - { - bassertfalse; // You shouldn't call this for an expression that's not actually a function! - return String::empty; - } - - virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth) - { - for (int i = getNumInputs(); --i >= 0;) - getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth); - } - - class SymbolVisitor - { - public: - virtual ~SymbolVisitor() {} - virtual void useSymbol (const Symbol&) = 0; - }; - - virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth) - { - for (int i = getNumInputs(); --i >= 0;) - getInput(i)->visitAllSymbols (visitor, scope, recursionDepth); - } -}; - - -//============================================================================== -struct Expression::Helpers -{ - typedef SharedPtr TermPtr; - - static void checkRecursionDepth (const int depth) - { - if (depth > 256) - throw EvaluationError ("Recursive symbol references"); - } - - friend class Expression::Term; - - //============================================================================== - /** An exception that can be thrown by Expression::evaluate(). */ - class EvaluationError : public std::exception - { - public: - EvaluationError (const String& desc) : description (desc) - { - BDBG ("Expression::EvaluationError: " + description); - } - - String description; - }; - - //============================================================================== - class Constant : public Term - { - public: - Constant (const double val, const bool resolutionTarget) - : value (val), isResolutionTarget (resolutionTarget) {} - - Type getType() const noexcept { return constantType; } - Term* clone() const { return new Constant (value, isResolutionTarget); } - TermPtr resolve (const Scope&, int) { return this; } - double toDouble() const { return value; } - TermPtr negated() { return new Constant (-value, isResolutionTarget); } - - String toString() const - { - String s (value); - if (isResolutionTarget) - s = "@" + s; - - return s; - } - - double value; - bool isResolutionTarget; - }; - - //============================================================================== - class BinaryTerm : public Term - { - public: - BinaryTerm (Term* const l, Term* const r) : left (l), right (r) - { - bassert (l != nullptr && r != nullptr); - } - - int getInputIndexFor (const Term* possibleInput) const - { - return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1); - } - - Type getType() const noexcept { return operatorType; } - int getNumInputs() const { return 2; } - Term* getInput (int index) const { return index == 0 ? left.get() : (index == 1 ? right.get() : 0); } - - virtual double performFunction (double left, double right) const = 0; - virtual void writeOperator (String& dest) const = 0; - - TermPtr resolve (const Scope& scope, int recursionDepth) - { - return new Constant (performFunction (left ->resolve (scope, recursionDepth)->toDouble(), - right->resolve (scope, recursionDepth)->toDouble()), false); - } - - String toString() const - { - String s; - - const int ourPrecendence = getOperatorPrecedence(); - if (left->getOperatorPrecedence() > ourPrecendence) - s << '(' << left->toString() << ')'; - else - s = left->toString(); - - writeOperator (s); - - if (right->getOperatorPrecedence() >= ourPrecendence) - s << '(' << right->toString() << ')'; - else - s << right->toString(); - - return s; - } - - protected: - const TermPtr left, right; - - TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const - { - bassert (input == left || input == right); - if (input != left && input != right) - return TermPtr(); - - const Term* const dest = findDestinationFor (topLevelTerm, this); - - if (dest == nullptr) - return new Constant (overallTarget, false); - - return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm); - } - }; - - //============================================================================== - class SymbolTerm : public Term - { - public: - explicit SymbolTerm (const String& sym) : symbol (sym) {} - - TermPtr resolve (const Scope& scope, int recursionDepth) - { - checkRecursionDepth (recursionDepth); - return scope.getSymbolValue (symbol).term->resolve (scope, recursionDepth + 1); - } - - Type getType() const noexcept { return symbolType; } - Term* clone() const { return new SymbolTerm (symbol); } - String toString() const { return symbol; } - String getName() const { return symbol; } - - void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth) - { - checkRecursionDepth (recursionDepth); - visitor.useSymbol (Symbol (scope.getScopeUID(), symbol)); - scope.getSymbolValue (symbol).term->visitAllSymbols (visitor, scope, recursionDepth + 1); - } - - void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/) - { - if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID) - symbol = newName; - } - - String symbol; - }; - - //============================================================================== - class Function : public Term - { - public: - explicit Function (const String& name) : functionName (name) {} - - Function (const String& name, const Array& params) - : functionName (name), parameters (params) - {} - - Type getType() const noexcept { return functionType; } - Term* clone() const { return new Function (functionName, parameters); } - int getNumInputs() const { return parameters.size(); } - Term* getInput (int i) const { return parameters.getReference(i).term; } - String getName() const { return functionName; } - - TermPtr resolve (const Scope& scope, int recursionDepth) - { - checkRecursionDepth (recursionDepth); - double result = 0; - const int numParams = parameters.size(); - if (numParams > 0) - { - HeapBlock params ((size_t) numParams); - for (int i = 0; i < numParams; ++i) - params[i] = parameters.getReference(i).term->resolve (scope, recursionDepth + 1)->toDouble(); - - result = scope.evaluateFunction (functionName, params, numParams); - } - else - { - result = scope.evaluateFunction (functionName, nullptr, 0); - } - - return new Constant (result, false); - } - - int getInputIndexFor (const Term* possibleInput) const - { - for (int i = 0; i < parameters.size(); ++i) - if (parameters.getReference(i).term == possibleInput) - return i; - - return -1; - } - - String toString() const - { - if (parameters.size() == 0) - return functionName + "()"; - - String s (functionName + " ("); - - for (int i = 0; i < parameters.size(); ++i) - { - s << parameters.getReference(i).term->toString(); - - if (i < parameters.size() - 1) - s << ", "; - } - - s << ')'; - return s; - } - - const String functionName; - Array parameters; - }; - - //============================================================================== - class DotOperator - : public BinaryTerm - { - public: - DotOperator (SymbolTerm* const l, Term* const r) : BinaryTerm (l, r) {} - - TermPtr resolve (const Scope& scope, int recursionDepth) - { - checkRecursionDepth (recursionDepth); - - EvaluationVisitor visitor (right, recursionDepth + 1); - scope.visitRelativeScope (getSymbol()->symbol, visitor); - return visitor.output; - } - - Term* clone() const { return new DotOperator (getSymbol(), right); } - String getName() const { return "."; } - int getOperatorPrecedence() const { return 1; } - void writeOperator (String& dest) const { dest << '.'; } - double performFunction (double, double) const { return 0.0; } - - void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth) - { - checkRecursionDepth (recursionDepth); - visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol)); - - SymbolVisitingVisitor v (right, visitor, recursionDepth + 1); - - try - { - scope.visitRelativeScope (getSymbol()->symbol, v); - } - catch (...) {} - } - - void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth) - { - checkRecursionDepth (recursionDepth); - getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth); - - SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1); - - try - { - scope.visitRelativeScope (getSymbol()->symbol, visitor); - } - catch (...) {} - } - - private: - //============================================================================== - class EvaluationVisitor - : public Scope::Visitor - , public Uncopyable - { - public: - EvaluationVisitor (const TermPtr& t, const int recursion) - : input (t), output (t), recursionCount (recursion) {} - - void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); } - - const TermPtr input; - TermPtr output; - const int recursionCount; - }; - - class SymbolVisitingVisitor - : public Scope::Visitor - , public Uncopyable - { - public: - SymbolVisitingVisitor (const TermPtr& t, SymbolVisitor& v, const int recursion) - : input (t), visitor (v), recursionCount (recursion) {} - - void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); } - - private: - const TermPtr input; - SymbolVisitor& visitor; - const int recursionCount; - }; - - class SymbolRenamingVisitor - : public Scope::Visitor - , public Uncopyable - { - public: - SymbolRenamingVisitor (const TermPtr& t, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_) - : input (t), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {} - - void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); } - - private: - const TermPtr input; - const Symbol& symbol; - const String newName; - const int recursionCount; - }; - - SymbolTerm* getSymbol() const { return static_cast (left.get()); } - }; - - //============================================================================== - class Negate : public Term - { - public: - explicit Negate (const TermPtr& t) : input (t) - { - bassert (t != nullptr); - } - - Type getType() const noexcept { return operatorType; } - int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; } - int getNumInputs() const { return 1; } - Term* getInput (int index) const { return index == 0 ? input.get() : nullptr; } - Term* clone() const { return new Negate (input->clone()); } - - TermPtr resolve (const Scope& scope, int recursionDepth) - { - return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false); - } - - String getName() const { return "-"; } - TermPtr negated() { return input; } - - TermPtr createTermToEvaluateInput (const Scope& scope, const Term* t, double overallTarget, Term* topLevelTerm) const - { - (void) t; - bassert (t == input); - - const Term* const dest = findDestinationFor (topLevelTerm, this); - - return new Negate (dest == nullptr ? new Constant (overallTarget, false) - : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm)); - } - - String toString() const - { - if (input->getOperatorPrecedence() > 0) - return "-(" + input->toString() + ")"; - - return "-" + input->toString(); - } - - private: - const TermPtr input; - }; - - //============================================================================== - class Add : public BinaryTerm - { - public: - Add (Term* const l, Term* const r) : BinaryTerm (l, r) {} - - Term* clone() const { return new Add (left->clone(), right->clone()); } - double performFunction (double lhs, double rhs) const { return lhs + rhs; } - int getOperatorPrecedence() const { return 3; } - String getName() const { return "+"; } - void writeOperator (String& dest) const { dest << " + "; } - - TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const - { - const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm)); - if (newDest == nullptr) - return TermPtr(); - - return new Subtract (newDest, (input == left ? right : left)->clone()); - } - }; - - //============================================================================== - class Subtract : public BinaryTerm - { - public: - Subtract (Term* const l, Term* const r) : BinaryTerm (l, r) {} - - Term* clone() const { return new Subtract (left->clone(), right->clone()); } - double performFunction (double lhs, double rhs) const { return lhs - rhs; } - int getOperatorPrecedence() const { return 3; } - String getName() const { return "-"; } - void writeOperator (String& dest) const { dest << " - "; } - - TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const - { - const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm)); - if (newDest == nullptr) - return TermPtr(); - - if (input == left) - return new Add (newDest, right->clone()); - - return new Subtract (left->clone(), newDest); - } - }; - - //============================================================================== - class Multiply : public BinaryTerm - { - public: - Multiply (Term* const l, Term* const r) : BinaryTerm (l, r) {} - - Term* clone() const { return new Multiply (left->clone(), right->clone()); } - double performFunction (double lhs, double rhs) const { return lhs * rhs; } - String getName() const { return "*"; } - void writeOperator (String& dest) const { dest << " * "; } - int getOperatorPrecedence() const { return 2; } - - TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const - { - const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm)); - if (newDest == nullptr) - return TermPtr(); - - return new Divide (newDest, (input == left ? right : left)->clone()); - } - }; - - //============================================================================== - class Divide : public BinaryTerm - { - public: - Divide (Term* const l, Term* const r) : BinaryTerm (l, r) {} - - Term* clone() const { return new Divide (left->clone(), right->clone()); } - double performFunction (double lhs, double rhs) const { return lhs / rhs; } - String getName() const { return "/"; } - void writeOperator (String& dest) const { dest << " / "; } - int getOperatorPrecedence() const { return 2; } - - TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const - { - const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm)); - if (newDest == nullptr) - return TermPtr(); - - if (input == left) - return new Multiply (newDest, right->clone()); - - return new Divide (left->clone(), newDest); - } - }; - - //============================================================================== - static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm) - { - const int inputIndex = topLevel->getInputIndexFor (inputTerm); - if (inputIndex >= 0) - return topLevel; - - for (int i = topLevel->getNumInputs(); --i >= 0;) - { - Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm); - - if (t != nullptr) - return t; - } - - return nullptr; - } - - static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged) - { - bassert (term != nullptr); - - if (term->getType() == constantType) - { - Constant* const c = static_cast (term); - if (c->isResolutionTarget || ! mustBeFlagged) - return c; - } - - if (term->getType() == functionType) - return nullptr; - - const int numIns = term->getNumInputs(); - - for (int i = 0; i < numIns; ++i) - { - Term* const input = term->getInput (i); - - if (input->getType() == constantType) - { - Constant* const c = static_cast (input); - - if (c->isResolutionTarget || ! mustBeFlagged) - return c; - } - } - - for (int i = 0; i < numIns; ++i) - { - Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged); - if (c != nullptr) - return c; - } - - return nullptr; - } - - static bool containsAnySymbols (const Term* const t) - { - if (t->getType() == Expression::symbolType) - return true; - - for (int i = t->getNumInputs(); --i >= 0;) - if (containsAnySymbols (t->getInput (i))) - return true; - - return false; - } - - //============================================================================== - class SymbolCheckVisitor - : public Term::SymbolVisitor - , public Uncopyable - { - public: - SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {} - void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; } - - bool wasFound; - - private: - const Symbol& symbol; - }; - - //============================================================================== - class SymbolListVisitor - : public Term::SymbolVisitor - , public Uncopyable - { - public: - SymbolListVisitor (Array& list_) : list (list_) {} - void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); } - - private: - Array& list; - }; - - //============================================================================== - class Parser : public Uncopyable - { - public: - //============================================================================== - Parser (String::CharPointerType& stringToParse) - : text (stringToParse) - { - } - - TermPtr readUpToComma() - { - if (text.isEmpty()) - return new Constant (0.0, false); - - const TermPtr e (readExpression()); - - if (e == nullptr || ((! readOperator (",")) && ! text.isEmpty())) - throw ParseError ("Syntax error: \"" + String (text) + "\""); - - return e; - } - - private: - String::CharPointerType& text; - - //============================================================================== - static inline bool isDecimalDigit (const beast_wchar c) noexcept - { - return c >= '0' && c <= '9'; - } - - bool readChar (const beast_wchar required) noexcept - { - if (*text == required) - { - ++text; - return true; - } - - return false; - } - - bool readOperator (const char* ops, char* const opType = nullptr) noexcept - { - text = text.findEndOfWhitespace(); - - while (*ops != 0) - { - if (readChar ((beast_wchar) (uint8) *ops)) - { - if (opType != nullptr) - *opType = *ops; - - return true; - } - - ++ops; - } - - return false; - } - - bool readIdentifier (String& identifier) noexcept - { - text = text.findEndOfWhitespace(); - String::CharPointerType t (text); - int numChars = 0; - - if (t.isLetter() || *t == '_') - { - ++t; - ++numChars; - - while (t.isLetterOrDigit() || *t == '_') - { - ++t; - ++numChars; - } - } - - if (numChars > 0) - { - identifier = String (text, (size_t) numChars); - text = t; - return true; - } - - return false; - } - - Term* readNumber() noexcept - { - text = text.findEndOfWhitespace(); - String::CharPointerType t (text); - - const bool isResolutionTarget = (*t == '@'); - if (isResolutionTarget) - { - ++t; - t = t.findEndOfWhitespace(); - text = t; - } - - if (*t == '-') - { - ++t; - t = t.findEndOfWhitespace(); - } - - if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1]))) - return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget); - - return nullptr; - } - - TermPtr readExpression() - { - TermPtr lhs (readMultiplyOrDivideExpression()); - - char opType; - while (lhs != nullptr && readOperator ("+-", &opType)) - { - TermPtr rhs (readMultiplyOrDivideExpression()); - - if (rhs == nullptr) - throw ParseError ("Expected expression after \"" + String::charToString ((beast_wchar) (uint8) opType) + "\""); - - if (opType == '+') - lhs = new Add (lhs, rhs); - else - lhs = new Subtract (lhs, rhs); - } - - return lhs; - } - - TermPtr readMultiplyOrDivideExpression() - { - TermPtr lhs (readUnaryExpression()); - - char opType; - while (lhs != nullptr && readOperator ("*/", &opType)) - { - TermPtr rhs (readUnaryExpression()); - - if (rhs == nullptr) - throw ParseError ("Expected expression after \"" + String::charToString ((beast_wchar) (uint8) opType) + "\""); - - if (opType == '*') - lhs = new Multiply (lhs, rhs); - else - lhs = new Divide (lhs, rhs); - } - - return lhs; - } - - TermPtr readUnaryExpression() - { - char opType; - if (readOperator ("+-", &opType)) - { - TermPtr e (readUnaryExpression()); - - if (e == nullptr) - throw ParseError ("Expected expression after \"" + String::charToString ((beast_wchar) (uint8) opType) + "\""); - - if (opType == '-') - e = e->negated(); - - return e; - } - - return readPrimaryExpression(); - } - - TermPtr readPrimaryExpression() - { - TermPtr e (readParenthesisedExpression()); - if (e != nullptr) - return e; - - e = readNumber(); - if (e != nullptr) - return e; - - return readSymbolOrFunction(); - } - - TermPtr readSymbolOrFunction() - { - String identifier; - if (readIdentifier (identifier)) - { - if (readOperator ("(")) // method call... - { - Function* const f = new Function (identifier); - ScopedPointer func (f); // (can't use ScopedPointer in MSVC) - - TermPtr param (readExpression()); - - if (param == nullptr) - { - if (readOperator (")")) - return func.release(); - - throw ParseError ("Expected parameters after \"" + identifier + " (\""); - } - - f->parameters.add (Expression (param)); - - while (readOperator (",")) - { - param = readExpression(); - - if (param == nullptr) - throw ParseError ("Expected expression after \",\""); - - f->parameters.add (Expression (param)); - } - - if (readOperator (")")) - return func.release(); - - throw ParseError ("Expected \")\""); - } - - if (readOperator (".")) - { - TermPtr rhs (readSymbolOrFunction()); - - if (rhs == nullptr) - throw ParseError ("Expected symbol or function after \".\""); - - if (identifier == "this") - return rhs; - - return new DotOperator (new SymbolTerm (identifier), rhs); - } - - // just a symbol.. - bassert (identifier.trim() == identifier); - return new SymbolTerm (identifier); - } - - return TermPtr(); - } - - TermPtr readParenthesisedExpression() - { - if (! readOperator ("(")) - return TermPtr(); - - const TermPtr e (readExpression()); - if (e == nullptr || ! readOperator (")")) - return TermPtr(); - - return e; - } - }; -}; - -//============================================================================== -Expression::Expression() - : term (new Expression::Helpers::Constant (0, false)) -{ -} - -Expression::~Expression() -{ -} - -Expression::Expression (Term* const term_) - : term (term_) -{ - bassert (term != nullptr); -} - -Expression::Expression (const double constant) - : term (new Expression::Helpers::Constant (constant, false)) -{ -} - -Expression::Expression (const Expression& other) - : term (other.term) -{ -} - -Expression& Expression::operator= (const Expression& other) -{ - term = other.term; - return *this; -} - -#if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS -Expression::Expression (Expression&& other) noexcept - : term (static_cast &&> (other.term)) -{ -} - -Expression& Expression::operator= (Expression&& other) noexcept -{ - term = static_cast &&> (other.term); - return *this; -} -#endif - -Expression::Expression (const String& stringToParse) -{ - String::CharPointerType text (stringToParse.getCharPointer()); - Helpers::Parser parser (text); - term = parser.readUpToComma(); -} - -Expression Expression::parse (String::CharPointerType& stringToParse) -{ - Helpers::Parser parser (stringToParse); - return Expression (parser.readUpToComma()); -} - -double Expression::evaluate() const -{ - return evaluate (Expression::Scope()); -} - -double Expression::evaluate (const Expression::Scope& scope) const -{ - try - { - return term->resolve (scope, 0)->toDouble(); - } - catch (Helpers::EvaluationError&) - {} - - return 0; -} - -double Expression::evaluate (const Scope& scope, String& evaluationError) const -{ - try - { - return term->resolve (scope, 0)->toDouble(); - } - catch (Helpers::EvaluationError& e) - { - evaluationError = e.description; - } - - return 0; -} - -Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); } -Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); } -Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); } -Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); } -Expression Expression::operator-() const { return Expression (term->negated()); } -Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); } - -Expression Expression::function (const String& functionName, const Array& parameters) -{ - return Expression (new Helpers::Function (functionName, parameters)); -} - -Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const -{ - ScopedPointer newTerm (term->clone()); - - Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true); - - if (termToAdjust == nullptr) - termToAdjust = Helpers::findTermToAdjust (newTerm, false); - - if (termToAdjust == nullptr) - { - newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false)); - termToAdjust = Helpers::findTermToAdjust (newTerm, false); - } - - bassert (termToAdjust != nullptr); - - const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust); - - if (parent == nullptr) - { - termToAdjust->value = targetValue; - } - else - { - const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm)); - - if (reverseTerm == nullptr) - return Expression (targetValue); - - termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble(); - } - - return Expression (newTerm.release()); -} - -Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const -{ - bassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_")); - - if (oldSymbol.symbolName == newName) - return *this; - - Expression e (term->clone()); - e.term->renameSymbol (oldSymbol, newName, scope, 0); - return e; -} - -bool Expression::referencesSymbol (const Expression::Symbol& symbolToCheck, const Scope& scope) const -{ - Helpers::SymbolCheckVisitor visitor (symbolToCheck); - - try - { - term->visitAllSymbols (visitor, scope, 0); - } - catch (Helpers::EvaluationError&) - {} - - return visitor.wasFound; -} - -void Expression::findReferencedSymbols (Array& results, const Scope& scope) const -{ - try - { - Helpers::SymbolListVisitor visitor (results); - term->visitAllSymbols (visitor, scope, 0); - } - catch (Helpers::EvaluationError&) - {} -} - -String Expression::toString() const { return term->toString(); } -bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); } -Expression::Type Expression::getType() const noexcept { return term->getType(); } -String Expression::getSymbolOrFunction() const { return term->getName(); } -int Expression::getNumInputs() const { return term->getNumInputs(); } -Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); } - -//============================================================================== -SharedPtr Expression::Term::negated() -{ - return new Helpers::Negate (this); -} - -//============================================================================== -Expression::ParseError::ParseError (const String& message) - : description (message) -{ - BDBG ("Expression::ParseError: " + message); -} - -//============================================================================== -Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_) - : scopeUID (scopeUID_), symbolName (symbolName_) -{ -} - -bool Expression::Symbol::operator== (const Symbol& other) const noexcept -{ - return symbolName == other.symbolName && scopeUID == other.scopeUID; -} - -bool Expression::Symbol::operator!= (const Symbol& other) const noexcept -{ - return ! operator== (other); -} - -//============================================================================== -Expression::Scope::Scope() {} -Expression::Scope::~Scope() {} - -Expression Expression::Scope::getSymbolValue (const String& symbol) const -{ - if (symbol.isNotEmpty()) - throw Helpers::EvaluationError ("Unknown symbol: " + symbol); - - return Expression(); -} - -double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const -{ - if (numParams > 0) - { - if (functionName == "min") - { - double v = parameters[0]; - for (int i = 1; i < numParams; ++i) - v = bmin (v, parameters[i]); - - return v; - } - - if (functionName == "max") - { - double v = parameters[0]; - for (int i = 1; i < numParams; ++i) - v = bmax (v, parameters[i]); - - return v; - } - - if (numParams == 1) - { - if (functionName == "sin") return sin (parameters[0]); - if (functionName == "cos") return cos (parameters[0]); - if (functionName == "tan") return tan (parameters[0]); - if (functionName == "abs") return std::abs (parameters[0]); - } - } - - throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\""); -} - -void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const -{ - throw Helpers::EvaluationError ("Unknown symbol: " + scopeName); -} - -String Expression::Scope::getScopeUID() const -{ - return String::empty; -} diff --git a/src/beast/modules/beast_core/maths/Expression.h b/src/beast/modules/beast_core/maths/Expression.h deleted file mode 100644 index d72a499c09..0000000000 --- a/src/beast/modules/beast_core/maths/Expression.h +++ /dev/null @@ -1,264 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Portions of this file are from JUCE. - Copyright (c) 2013 - Raw Material Software Ltd. - Please visit http://www.juce.com - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_EXPRESSION_H_INCLUDED -#define BEAST_EXPRESSION_H_INCLUDED - -//============================================================================== -/** - A class for dynamically evaluating simple numeric expressions. - - This class can parse a simple C-style string expression involving floating point - numbers, named symbols and functions. The basic arithmetic operations of +, -, *, / - are supported, as well as parentheses, and any alphanumeric identifiers are - assumed to be named symbols which will be resolved when the expression is - evaluated. - - Expressions which use identifiers and functions require a subclass of - Expression::Scope to be supplied when evaluating them, and this object - is expected to be able to resolve the symbol names and perform the functions that - are used. -*/ -class BEAST_API Expression -{ -public: - //============================================================================== - /** Creates a simple expression with a value of 0. */ - Expression(); - - /** Destructor. */ - ~Expression(); - - /** Creates a simple expression with a specified constant value. */ - explicit Expression (double constant); - - /** Creates a copy of an expression. */ - Expression (const Expression& other); - - /** Copies another expression. */ - Expression& operator= (const Expression& other); - - #if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS - Expression (Expression&& other) noexcept; - Expression& operator= (Expression&& other) noexcept; - #endif - - /** Creates an expression by parsing a string. - If there's a syntax error in the string, this will throw a ParseError exception. - @throws ParseError - */ - explicit Expression (const String& stringToParse); - - /** Returns a string version of the expression. */ - String toString() const; - - /** Returns an expression which is an addtion operation of two existing expressions. */ - Expression operator+ (const Expression& other) const; - /** Returns an expression which is a subtraction operation of two existing expressions. */ - Expression operator- (const Expression& other) const; - /** Returns an expression which is a multiplication operation of two existing expressions. */ - Expression operator* (const Expression& other) const; - /** Returns an expression which is a division operation of two existing expressions. */ - Expression operator/ (const Expression& other) const; - /** Returns an expression which performs a negation operation on an existing expression. */ - Expression operator-() const; - - /** Returns an Expression which is an identifier reference. */ - static Expression symbol (const String& symbol); - - /** Returns an Expression which is a function call. */ - static Expression function (const String& functionName, const Array& parameters); - - /** Returns an Expression which parses a string from a character pointer, and updates the pointer - to indicate where it finished. - - The pointer is incremented so that on return, it indicates the character that follows - the end of the expression that was parsed. - - If there's a syntax error in the string, this will throw a ParseError exception. - @throws ParseError - */ - static Expression parse (String::CharPointerType& stringToParse); - - //============================================================================== - /** When evaluating an Expression object, this class is used to resolve symbols and - perform functions that the expression uses. - */ - class BEAST_API Scope - { - public: - Scope(); - virtual ~Scope(); - - /** Returns some kind of globally unique ID that identifies this scope. */ - virtual String getScopeUID() const; - - /** Returns the value of a symbol. - If the symbol is unknown, this can throw an Expression::EvaluationError exception. - The member value is set to the part of the symbol that followed the dot, if there is - one, e.g. for "foo.bar", symbol = "foo" and member = "bar". - @throws Expression::EvaluationError - */ - virtual Expression getSymbolValue (const String& symbol) const; - - /** Executes a named function. - If the function name is unknown, this can throw an Expression::EvaluationError exception. - @throws Expression::EvaluationError - */ - virtual double evaluateFunction (const String& functionName, - const double* parameters, int numParameters) const; - - /** Used as a callback by the Scope::visitRelativeScope() method. - You should never create an instance of this class yourself, it's used by the - expression evaluation code. - */ - class Visitor - { - public: - virtual ~Visitor() {} - virtual void visit (const Scope&) = 0; - }; - - /** Creates a Scope object for a named scope, and then calls a visitor - to do some kind of processing with this new scope. - - If the name is valid, this method must create a suitable (temporary) Scope - object to represent it, and must call the Visitor::visit() method with this - new scope. - */ - virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const; - }; - - /** Evaluates this expression, without using a Scope. - Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan, - min, max are available. - To find out about any errors during evaluation, use the other version of this method which - takes a String parameter. - */ - double evaluate() const; - - /** Evaluates this expression, providing a scope that should be able to evaluate any symbols - or functions that it uses. - To find out about any errors during evaluation, use the other version of this method which - takes a String parameter. - */ - double evaluate (const Scope& scope) const; - - /** Evaluates this expression, providing a scope that should be able to evaluate any symbols - or functions that it uses. - */ - double evaluate (const Scope& scope, String& evaluationError) const; - - /** Attempts to return an expression which is a copy of this one, but with a constant adjusted - to make the expression resolve to a target value. - - E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return - the expression "x + 3". Obviously some expressions can't be reversed in this way, in which - case they might just be adjusted by adding a constant to the original expression. - - @throws Expression::EvaluationError - */ - Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const; - - /** Represents a symbol that is used in an Expression. */ - struct Symbol - { - Symbol (const String& scopeUID, const String& symbolName); - bool operator== (const Symbol&) const noexcept; - bool operator!= (const Symbol&) const noexcept; - - String scopeUID; /**< The unique ID of the Scope that contains this symbol. */ - String symbolName; /**< The name of the symbol. */ - }; - - /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */ - Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const; - - /** Returns true if this expression makes use of the specified symbol. - If a suitable scope is supplied, the search will dereference and recursively check - all symbols, so that it can be determined whether this expression relies on the given - symbol at any level in its evaluation. If the scope parameter is null, this just checks - whether the expression contains any direct references to the symbol. - - @throws Expression::EvaluationError - */ - bool referencesSymbol (const Symbol& symbol, const Scope& scope) const; - - /** Returns true if this expression contains any symbols. */ - bool usesAnySymbols() const; - - /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */ - void findReferencedSymbols (Array& results, const Scope& scope) const; - - //============================================================================== - /** An exception that can be thrown by Expression::parse(). */ - class ParseError : public std::exception - { - public: - ParseError (const String& message); - - String description; - }; - - //============================================================================== - /** Expression type. - @see Expression::getType() - */ - enum Type - { - constantType, - functionType, - operatorType, - symbolType - }; - - /** Returns the type of this expression. */ - Type getType() const noexcept; - - /** If this expression is a symbol, function or operator, this returns its identifier. */ - String getSymbolOrFunction() const; - - /** Returns the number of inputs to this expression. - @see getInput - */ - int getNumInputs() const; - - /** Retrieves one of the inputs to this expression. - @see getNumInputs - */ - Expression getInput (int index) const; - -private: - //============================================================================== - class Term; - struct Helpers; - friend class Term; - friend struct Helpers; - friend class ScopedPointer; - friend class SharedPtr; - SharedPtr term; - - explicit Expression (Term*); -}; - -#endif // BEAST_EXPRESSION_H_INCLUDED diff --git a/src/beast/modules/beast_core/maths/Interval.h b/src/beast/modules/beast_core/maths/Interval.h deleted file mode 100644 index 833af4551e..0000000000 --- a/src/beast/modules/beast_core/maths/Interval.h +++ /dev/null @@ -1,387 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_INTERVAL_H_INCLUDED -#define BEAST_INTERVAL_H_INCLUDED - -/** A half-open interval. - - This represents the half-open interval [begin, end) over the scalar - type of template parameter `Ty`. It may also be considered as the - specification of a subset of a 1-dimensional Euclidean space. - - @tparam Ty A scalar numerical type. -*/ -template -class Interval -{ -public: - typedef Ty value_type; - - /** The empty interval. - */ - static const Interval none; - - /** Create an uninitialized interval. - */ - Interval () - { - } - - /** Create an interval with the specified values. - */ - Interval (Ty begin, Ty end) - : m_begin (begin) - , m_end (end) - { - } - - /** Create an interval from another interval. - */ - Interval (Interval const& other) - : m_begin (other.m_begin) - , m_end (other.m_end) - { - } - - /** Assign from another interval. - - @param other The interval to assign from. - - @return A reference to this interval. - */ - Interval& operator= (const Interval& other) - { - m_begin = other.m_begin; - m_end = other.m_end; - return *this; - } - - /** Compare an interval for equality. - - Empty intervals are always equal to other empty intervals. - - @param rhs The other interval to compare. - - @return `true` if this interval is equal to the specified interval. - */ - bool operator== (Interval const& rhs) const - { - return (empty () && rhs.empty ()) || - (m_begin == rhs.m_begin && m_end == rhs.m_end); - } - - /** Compare an interval for inequality. - - @param rhs The other interval to compare. - - @return `true` if this interval is not equal to the specified interval. - */ - bool operator!= (Interval const& rhs) const - { - return !this->operator== (rhs); - } - - /** Get the starting value of the interval. - - @return The starting point of the interval. - */ - Ty begin () const - { - return m_begin; - } - - /** Get the ending value of the interval. - - @return The ending point of the interval. - */ - Ty end () const - { - return m_end; - } - - /** Get the Lebesque measure. - - @return The Lebesque measure. - */ - Ty length () const - { - return empty () ? Ty () : (end () - begin ()); - } - - //Ty count () const { return length (); } // sugar - //Ty distance () const { return length (); } // sugar - - /** Determine if the interval is empty. - - @return `true` if the interval is empty. - */ - bool empty () const - { - return m_begin >= m_end; - } - - /** Determine if the interval is non-empty. - - @return `true` if the interval is not empty. - */ - bool notEmpty () const - { - return m_begin < m_end; - } - - /** Set the starting point of the interval. - - @param v The starting point. - */ - void setBegin (Ty v) - { - m_begin = v; - } - - /** Set the ending point of the interval. - - @param v The ending point. - */ - void setEnd (Ty v) - { - m_end = v; - } - - /** Set the ending point relative to the starting point. - - @param v The length of the resulting interval. - */ - void setLength (Ty v) - { - m_end = m_begin + v; - } - - /** Determine if a value is contained in the interval. - - @param v The value to check. - - @return `true` if this interval contains `v`. - */ - bool contains (Ty v) const - { - return notEmpty () && v >= m_begin && v < m_end; - } - - /** Determine if this interval intersects another interval. - - @param other The other interval. - - @return `true` if the intervals intersect. - */ - template - bool intersects (Interval const& other) const - { - return notEmpty () && other.notEmpty () && - end () > other.begin () && begin () < other.end (); - } - - /** Determine if this interval adjoins another interval. - - An interval is adjoint to another interval if and only if the union of the - intervals is a single non-empty half-open subset. - - @param other The other interval. - - @return `true` if the intervals are adjoint. - */ - template - bool adjoins (Interval const& other) const - { - return (empty () != other.empty ()) || - (notEmpty () && end () >= other.begin () - && begin () <= other.end ()); - } - - /** Determine if this interval is disjoint from another interval. - - @param other The other interval. - - @return `true` if the intervals are disjoint. - */ - bool disjoint (Interval const& other) const - { - return !intersects (other); - } - - /** Determine if this interval is a superset of another interval. - - An interval A is a superset of interval B if B is empty or if A fully - contains B. - - @param other The other interval. - - @return `true` if this is a superset of `other`. - */ - template - bool superset_of (Interval const& other) const - { - return other.empty () || - (notEmpty () && begin () <= other.begin () - && end () >= other.end ()); - } - - /** Determine if this interval is a proper superset of another interval. - - An interval A is a proper superset of interval B if A is a superset of - B and A is not equal to B. - - @param other The other interval. - - @return `true` if this interval is a proper superset of `other`. - */ - template - bool proper_superset_of (Interval const& other) const - { - return this->superset_of (other) && this->operator != (other); - } - - /** Determine if this interval is a subset of another interval. - - @param other The other interval. - - @return `true` if this interval is a subset of `other`. - */ - template - bool subset_of (Interval const& other) const - { - return other.superset_of (*this); - } - - /** Determine if this interval is a proper subset of another interval. - - @param other The other interval. - - @return `true` if this interval is a proper subset of `other`. - */ - template - bool proper_subset_of (Interval const& other) const - { - return other.proper_superset_of (*this); - } - - /** Return the intersection of this interval with another interval. - - @param other The other interval. - - @return The intersection of the intervals. - */ - template - Interval intersection (Interval const& other) const - { - return Interval (std::max (begin (), other.begin ()), - std::min (end (), other.end ())); - } - - /** Determine the smallest interval that contains both intervals. - - @param other The other interval. - - @return The simple union of the intervals. - */ - template - Interval simple_union (Interval const& other) const - { - return Interval ( - std::min (other.normalized ().begin (), normalized ().begin ()), - std::max (other.normalized ().end (), normalized ().end ())); - } - - /** Calculate the single-interval union. - - The result is empty if the union cannot be represented as a - single half-open interval. - - @param other The other interval. - - @return The simple union of the intervals. - */ - template - Interval single_union (Interval const& other) const - { - if (empty ()) - return other; - - else if (other.empty ()) - return *this; - - else if (end () < other.begin () || begin () > other.end ()) - return none; - - else - return Interval (std::min (begin (), other.begin ()), - std::max (end (), other.end ())); - } - - /** Determine if the interval is correctly ordered. - - @return `true` if the interval is correctly ordered. - */ - bool normal () const - { - return end () >= begin (); - } - - /** Return a normalized interval. - - @return The normalized interval. - */ - Interval normalized () const - { - if (normal ()) - return *this; - else - return Interval (end (), begin ()); - } - - /** Clamp a value to the interval. - - @param v The value to clamp. - - @return The clamped result. - */ - template - Ty clamp (Tv v) const - { - // These conditionals are carefully ordered so - // that if m_begin == m_end, value is assigned m_begin. - if (v > end ()) - v = end () - (std::numeric_limits ::is_integer ? 1 : - std::numeric_limits ::epsilon ()); - - if (v < begin ()) - v = begin (); - - return v; - } - -private: - Ty m_begin; - Ty m_end; -}; - -template -const Interval Interval::none = Interval (Ty (), Ty ()); - -#endif diff --git a/src/beast/modules/beast_core/memory/AtomicCounter.h b/src/beast/modules/beast_core/memory/AtomicCounter.h deleted file mode 100644 index 0f03456cb8..0000000000 --- a/src/beast/modules/beast_core/memory/AtomicCounter.h +++ /dev/null @@ -1,83 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ATOMICCOUNTER_H_INCLUDED -#define BEAST_ATOMICCOUNTER_H_INCLUDED - -/*============================================================================*/ -/** - A thread safe usage counter. - - This provides a simplified interface to an atomic integer suitable for - measuring reference or usage counts. The counter is signaled when the - count is non zero. - - @ingroup beast_core -*/ -class BEAST_API AtomicCounter -{ -public: - /** Create a new counter. - - @param initialValue An optional starting usage count (default is 0). - */ - AtomicCounter (int initialValue = 0) noexcept -: - m_value (initialValue) - { - } - - /** Increment the usage count. - - @return `true` if the counter became signaled. - */ - inline bool addref () noexcept - { - return (++m_value) == 1; - } - - /** Decrements the usage count. - - @return `true` if the counter became non-signaled. - */ - inline bool release () noexcept - { - // Unfortunately, AllocatorWithoutTLS breaks this assert - //bassert (isSignaled ()); - - return (--m_value) == 0; - } - - /** Determine if the counter is signaled. - - Note that another thread can cause the counter to become reset after - this function returns true. - - @return `true` if the counter was signaled. - */ - inline bool isSignaled () const noexcept - { - return m_value.get () > 0; - } - -private: - Atomic m_value; -}; - -#endif diff --git a/src/beast/modules/beast_core/memory/AtomicFlag.h b/src/beast/modules/beast_core/memory/AtomicFlag.h deleted file mode 100644 index 6613ca123f..0000000000 --- a/src/beast/modules/beast_core/memory/AtomicFlag.h +++ /dev/null @@ -1,102 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ATOMICFLAG_H_INCLUDED -#define BEAST_ATOMICFLAG_H_INCLUDED - -/*============================================================================*/ -/** - A thread safe flag. - - This provides a simplified interface to an atomic integer suitable for - representing a flag. The flag is signaled when on, else it is considered - reset. - - @ingroup beast_core -*/ -class BEAST_API AtomicFlag -{ -public: - /** Create an AtomicFlag in the reset state. */ - AtomicFlag () noexcept -: - m_value (0) - { - } - - /** Signal the flag. - - If two or more threads simultaneously attempt to signal the flag, - only one will receive a true return value. - - @return true if the flag was previously reset. - */ - inline bool trySignal () noexcept - { - return m_value.compareAndSetBool (1, 0); - } - - /** Signal the flag. - - The flag must be in the reset state. Only one thread may - call this at a time. - */ - inline void signal () noexcept - { -#if BEAST_DEBUG - const bool success = m_value.compareAndSetBool (1, 0); - bassert (success); -#else - m_value.set (1); -#endif - } - - /** Reset the flag. - - The flag must be in the signaled state. Only one thread may - call this at a time. Usually it is the thread that was successful - in a previous call to trySignal(). - */ - inline void reset () noexcept - { -#if BEAST_DEBUG - const bool success = m_value.compareAndSetBool (0, 1); - bassert (success); -#else - m_value.set (0); -#endif - } - - /** Check if the AtomicFlag is signaled - - The signaled status may change immediately after this call - returns. The caller must synchronize. - - @return true if the flag was signaled. - */ - inline bool isSignaled () const noexcept - { - return m_value.get () == 1; - } - -private: - Atomic m_value; -}; - -#endif diff --git a/src/beast/modules/beast_core/memory/AtomicPointer.h b/src/beast/modules/beast_core/memory/AtomicPointer.h deleted file mode 100644 index 28ae3a0de9..0000000000 --- a/src/beast/modules/beast_core/memory/AtomicPointer.h +++ /dev/null @@ -1,133 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ATOMICPOINTER_H_INCLUDED -#define BEAST_ATOMICPOINTER_H_INCLUDED - -/*============================================================================*/ -/** - A thread safe pointer. - - This provides a simplified interface to an atomic pointer suitable - for building containers or composite classes. Operator overloads - allow access to the underlying pointer using natural C++ syntax. - - @ingroup beast_core -*/ -template -class AtomicPointer -{ -public: - /** Create a pointer. - - @param initialValue An optional starting value (default is null). - */ - explicit AtomicPointer (P* const initialValue = nullptr) noexcept -: - m_value (initialValue) - { - } - - /** Retrieve the pointer value */ - inline P* get () const noexcept - { - return m_value.get (); - } - - /** Obtain a pointer to P through type conversion. - - The caller must synchronize access to P. - - @return A pointer to P. - */ - inline operator P* () const noexcept - { - return get (); - } - - /** Dereference operator - - The caller must synchronize access to P. - - @return A reference to P. - */ - inline P& operator* () const noexcept - { - return &get (); - } - - /** Member selection - - The caller must synchronize access to P. - - @return A pointer to P. - */ - inline P* operator-> () const noexcept - { - return get (); - } - - inline void set (P* p) - { - m_value.set (p); - } - - /** Atomically assign a new pointer - - @param newValue The new value to assign. - */ - inline void operator= (P* newValue) noexcept - { - set (newValue); - } - - /** Atomically assign a new pointer and return the old value. - - @param newValue The new value to assign. - - @return The previous value. - */ - inline P* exchange (P* newValue) - { - return m_value.exchange (newValue); - } - - /** Conditionally perform an atomic assignment. - - The current value is compared with oldValue and atomically - set to newValue if the comparison is equal. - - The caller is responsible for handling the ABA problem. - - @param newValue The new value to assign. - - @param oldValue The matching old value. - - @return true if the assignment was performed. - */ - inline bool compareAndSet (P* newValue, P* oldValue) - { - return m_value.compareAndSetBool (newValue, oldValue); - } - -private: - Atomic m_value; -}; - -#endif diff --git a/src/beast/modules/beast_core/memory/AtomicState.h b/src/beast/modules/beast_core/memory/AtomicState.h deleted file mode 100644 index ec65aaada5..0000000000 --- a/src/beast/modules/beast_core/memory/AtomicState.h +++ /dev/null @@ -1,101 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ATOMICSTATE_H_INCLUDED -#define BEAST_ATOMICSTATE_H_INCLUDED - -/*============================================================================*/ -/** - A thread safe state variable. - - This provides a simplified interface to an integer used to control atomic - state transitions. A state is distinguished by a single integer value. - - @ingroup beast_core -*/ -class BEAST_API AtomicState -{ -public: - /** Create a new state with an optional starting value. - - @param initialState The initial state. - */ - - - explicit AtomicState (const int initialState = 0) noexcept -: - m_value (initialState) - { - } - - /** Retrieve the current state. - - This converts the object to an integer reflecting the current state. - - Note that other threads may change the value immediately after this - function returns. The caller is responsible for synchronizing. - - @return The state at the time of the call. - */ - inline operator int () const - { - return m_value.get (); - } - - /** Attempt a state transition. - - The current state is compared to `from`, and if the comparison is - successful the state becomes `to`. The entire operation is atomic. - - @param from The current state, for comparison. - - @param to The desired new state. - - @return true if the state transition succeeded. - */ - inline bool tryChangeState (const int from, const int to) noexcept - { - return m_value.compareAndSetBool (to, from); - } - - /** Perform a state transition. - - This attempts to change the state and generates a diagnostic on - failure. This routine can be used instead of tryChangeState() - when program logic requires that the state change must succeed. - - @param from The required current state. - - @param to The new state. - */ - inline void changeState (const int from, const int to) noexcept - { -#if BEAST_DEBUG - const bool success = tryChangeState (from, to); - bassert (success); -#else - tryChangeState (from, to); -#endif - } - -private: - Atomic m_value; -}; - -#endif diff --git a/src/beast/modules/beast_core/memory/RecycledObjectPool.h b/src/beast/modules/beast_core/memory/RecycledObjectPool.h deleted file mode 100644 index 6981427bf5..0000000000 --- a/src/beast/modules/beast_core/memory/RecycledObjectPool.h +++ /dev/null @@ -1,126 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_RECYCLEDOBJECTPOOL_H_INCLUDED -#define BEAST_RECYCLEDOBJECTPOOL_H_INCLUDED - -/** A pool of objects which may be recycled. - - This is a thread safe pool of objects that get re-used. It is - primarily designed to eliminate the need for many memory allocations - and frees when temporary buffers are needed for operations. - - To use it, first declare a structure containing the information - that you want to recycle. Then when you want to use a recycled object - put a ScopedItem on your stack: - - @code - - struct StdString - { - std::string data; - }; - - RecycledObjectPool pool; - - void foo () - { - RecycledObjectPool ::ScopedItem item; - - item.getObject ().data = "text"; - } - - @endcode -*/ -template -class RecycledObjectPool -{ -public: - struct Item : Object, LockFreeStack ::Node, LeakChecked - { - }; - - class ScopedItem - { - public: - explicit ScopedItem (RecycledObjectPool & pool) - : m_pool (pool) - , m_item (pool.get ()) - { - } - - ~ScopedItem () - { - m_pool.release (m_item); - } - - Object& getObject () noexcept - { - return *m_item; - } - - private: - RecycledObjectPool & m_pool; - Item* const m_item; - }; - -public: - RecycledObjectPool () noexcept - { - } - - ~RecycledObjectPool () - { - for (;;) - { - Item* const item = m_stack.pop_front (); - - if (item != nullptr) - delete item; - else - break; - } - } - -private: - Item* get () - { - Item* item = m_stack.pop_front (); - - if (item == nullptr) - { - item = new Item; - - if (item == nullptr) - Throw (std::bad_alloc ()); - } - - return item; - } - - void release (Item* item) noexcept - { - m_stack.push_front (item); - } - -private: - LockFreeStack m_stack; -}; - -#endif diff --git a/src/beast/modules/beast_core/memory/WeakReference.h b/src/beast/modules/beast_core/memory/WeakReference.h deleted file mode 100644 index 4ac3413997..0000000000 --- a/src/beast/modules/beast_core/memory/WeakReference.h +++ /dev/null @@ -1,204 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Portions of this file are from JUCE. - Copyright (c) 2013 - Raw Material Software Ltd. - Please visit http://www.juce.com - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WEAKREFERENCE_H_INCLUDED -#define BEAST_WEAKREFERENCE_H_INCLUDED - -//============================================================================== -/** - This class acts as a pointer which will automatically become null if the object - to which it points is deleted. - - To accomplish this, the source object needs to cooperate by performing a couple of simple tasks. - It must embed a WeakReference::Master object, which stores a shared pointer object, and must clear - this master pointer in its destructor. - - E.g. - @code - class MyObject - { - public: - MyObject() - { - // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose - // to create a WeakReference to the object here in the constructor, which will pre-initialise the - // embedded object, avoiding an (extremely unlikely) race condition that could occur if multiple - // threads overlap while creating the first WeakReference to it. - } - - ~MyObject() - { - // This will zero all the references - you need to call this in your destructor. - masterReference.clear(); - } - - private: - // You need to embed a variable of this type, with the name "masterReference" inside your object. If the - // variable is not public, you should make your class a friend of WeakReference so that the - // WeakReference class can access it. - WeakReference::Master masterReference; - friend class WeakReference; - }; - - // Here's an example of using a pointer.. - - MyObject* n = new MyObject(); - WeakReference myObjectRef = n; - - MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n' - delete n; - MyObject* pointer2 = myObjectRef; // returns a null pointer - @endcode - - @see WeakReference::Master -*/ -template -class WeakReference -{ -public: - /** Creates a null SafePointer. */ - inline WeakReference() noexcept {} - - /** Creates a WeakReference that points at the given object. */ - WeakReference (ObjectType* const object) : holder (getRef (object)) {} - - /** Creates a copy of another WeakReference. */ - WeakReference (const WeakReference& other) noexcept : holder (other.holder) {} - - /** Copies another pointer to this one. */ - WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; } - - /** Copies another pointer to this one. */ - WeakReference& operator= (ObjectType* const newObject) { holder = getRef (newObject); return *this; } - - #if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS - WeakReference (WeakReference&& other) noexcept : holder (static_cast (other.holder)) {} - WeakReference& operator= (WeakReference&& other) noexcept { holder = static_cast (other.holder); return *this; } - #endif - - /** Returns the object that this pointer refers to, or null if the object no longer exists. */ - ObjectType* get() const noexcept { return holder != nullptr ? holder->get() : nullptr; } - - /** Returns the object that this pointer refers to, or null if the object no longer exists. */ - operator ObjectType*() const noexcept { return get(); } - - /** Returns the object that this pointer refers to, or null if the object no longer exists. */ - ObjectType* operator->() noexcept { return get(); } - - /** Returns the object that this pointer refers to, or null if the object no longer exists. */ - const ObjectType* operator->() const noexcept { return get(); } - - /** This returns true if this reference has been pointing at an object, but that object has - since been deleted. - - If this reference was only ever pointing at a null pointer, this will return false. Using - operator=() to make this refer to a different object will reset this flag to match the status - of the reference from which you're copying. - */ - bool wasObjectDeleted() const noexcept { return holder != nullptr && holder->get() == nullptr; } - - bool operator== (ObjectType* const object) const noexcept { return get() == object; } - bool operator!= (ObjectType* const object) const noexcept { return get() != object; } - - //============================================================================== - /** This class is used internally by the WeakReference class - don't use it directly - in your code! - @see WeakReference - */ - class SharedPointer - : public ReferenceCountingType - , public Uncopyable - { - public: - explicit SharedPointer (ObjectType* const obj) noexcept : owner (obj) {} - - inline ObjectType* get() const noexcept { return owner; } - void clearPointer() noexcept { owner = nullptr; } - - private: - ObjectType* volatile owner; - }; - - typedef SharedPtr SharedRef; - - //============================================================================== - /** - This class is embedded inside an object to which you want to attach WeakReference pointers. - See the WeakReference class notes for an example of how to use this class. - @see WeakReference - */ - class Master : public Uncopyable - { - public: - Master() noexcept {} - - ~Master() - { - // You must remember to call clear() in your source object's destructor! See the notes - // for the WeakReference class for an example of how to do this. - bassert (sharedPointer == nullptr || sharedPointer->get() == nullptr); - } - - /** The first call to this method will create an internal object that is shared by all weak - references to the object. - */ - SharedPointer* getSharedPointer (ObjectType* const object) - { - if (sharedPointer == nullptr) - { - sharedPointer = new SharedPointer (object); - } - else - { - // You're trying to create a weak reference to an object that has already been deleted!! - bassert (sharedPointer->get() != nullptr); - } - - return sharedPointer; - } - - /** The object that owns this master pointer should call this before it gets destroyed, - to zero all the references to this object that may be out there. See the WeakReference - class notes for an example of how to do this. - */ - void clear() - { - if (sharedPointer != nullptr) - sharedPointer->clearPointer(); - } - - private: - SharedRef sharedPointer; - }; - -private: - SharedRef holder; - - static inline SharedPointer* getRef (ObjectType* const o) - { - return (o != nullptr) ? o->masterReference.getSharedPointer (o) : nullptr; - } -}; - - -#endif // BEAST_WEAKREFERENCE_H_INCLUDED diff --git a/src/beast/modules/beast_core/system/Functional.h b/src/beast/modules/beast_core/system/Functional.h index 9aabe28e95..f8aaba2c33 100644 --- a/src/beast/modules/beast_core/system/Functional.h +++ b/src/beast/modules/beast_core/system/Functional.h @@ -63,7 +63,8 @@ namespace functional using std::ref; using std::cref; using std::bind; -using std::function; + +//using std::function; } @@ -166,7 +167,8 @@ namespace functional using std::tr1::ref; using std::tr1::cref; using std::tr1::bind; -using std::tr1::function; + +//using std::tr1::function; } @@ -269,7 +271,8 @@ namespace functional using boost::ref; using boost::cref; using boost::bind; -using boost::function; + +//using boost::function; } diff --git a/src/beast/modules/beast_core/thread/Semaphore.cpp b/src/beast/modules/beast_core/thread/Semaphore.cpp deleted file mode 100644 index bf97ee5162..0000000000 --- a/src/beast/modules/beast_core/thread/Semaphore.cpp +++ /dev/null @@ -1,125 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -Semaphore::Semaphore (int initialCount) - : m_counter (initialCount) -{ -} - -Semaphore::~Semaphore () -{ - // Can't delete the semaphore while threads are waiting on it!! - bassert (m_waitingThreads.pop_front () == nullptr); - - for (;;) - { - WaitingThread* waitingThread = m_deleteList.pop_front (); - - if (waitingThread != nullptr) - delete waitingThread; - else - break; - } -} - -void Semaphore::signal (int amount) -{ - bassert (amount > 0); - - while (amount--) - { - // Make counter and list operations atomic. - LockType::ScopedLockType lock (m_mutex); - - if (++m_counter <= 0) - { - WaitingThread* waitingThread = m_waitingThreads.pop_front (); - - bassert (waitingThread != nullptr); - - waitingThread->signal (); - } - } -} - -bool Semaphore::wait (int timeOutMilliseconds) -{ - bool signaled = true; - - // Always prepare the WaitingThread object first, either - // from the delete list or through a new allocation. - // - WaitingThread* waitingThread = m_deleteList.pop_front (); - - if (waitingThread == nullptr) - waitingThread = new WaitingThread; - - { - // Make counter and list operations atomic. - LockType::ScopedLockType lock (m_mutex); - - if (--m_counter >= 0) - { - // Acquired the resource so put waitingThread back. - m_deleteList.push_front (waitingThread); - - waitingThread = nullptr; - } - else - { - // Out of resources, go on to the waiting list. - m_waitingThreads.push_front (waitingThread); - } - } - - // Do we need to wait? - if (waitingThread != nullptr) - { - // Yes so do it. - signaled = waitingThread->wait (timeOutMilliseconds); - - // If the wait is satisfied, then we've been taken off the - // waiting list so put waitingThread back in the delete list. - // - m_deleteList.push_front (waitingThread); - } - - return signaled; -} - -//------------------------------------------------------------------------------ - -Semaphore::WaitingThread::WaitingThread () - : m_event (false) // auto-reset -{ -} - -bool Semaphore::WaitingThread::wait (int timeOutMilliseconds) -{ - return m_event.wait (timeOutMilliseconds); -} - -void Semaphore::WaitingThread::signal () -{ - m_event.signal (); -} - -//------------------------------------------------------------------------------ - -// VFALCO TODO Unit Tests! diff --git a/src/beast/modules/beast_core/thread/Semaphore.h b/src/beast/modules/beast_core/thread/Semaphore.h deleted file mode 100644 index f261b51e0f..0000000000 --- a/src/beast/modules/beast_core/thread/Semaphore.h +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_SEMAPHORE_H_INCLUDED -#define BEAST_SEMAPHORE_H_INCLUDED - -/*============================================================================*/ -/** - A semaphore. - - This provides a traditional semaphore synchronization primitive. There is no - upper limit on the number of signals. - - @note There is no tryWait() or timeout facility for acquiring a resource. - - @ingroup beast_core -*/ -class BEAST_API Semaphore -{ -public: - /** Create a semaphore with the specified number of resources. - - @param initialCount The starting number of resources. - */ - explicit Semaphore (int initialCount = 0); - - ~Semaphore (); - - /** Increase the number of available resources. - - @param amount The number of new resources available. - */ - void signal (int amount = 1); - - /** Wait for a resource. - - A negative time-out value means that the method will wait indefinitely. - - @returns true if the event has been signalled, false if the timeout expires. - */ - bool wait (int timeOutMilliseconds = -1); - -private: - class WaitingThread - : public LockFreeStack ::Node - , LeakChecked - { - public: - WaitingThread (); - - bool wait (int timeOutMilliseconds); - void signal (); - - private: - WaitableEvent m_event; - }; - - typedef SpinLock LockType; - - LockType m_mutex; - Atomic m_counter; - LockFreeStack m_waitingThreads; - LockFreeStack m_deleteList; -}; - -#endif diff --git a/src/beast/modules/beast_core/thread/Workers.h b/src/beast/modules/beast_core/thread/Workers.h index d56b74017d..ff2a31fba8 100644 --- a/src/beast/modules/beast_core/thread/Workers.h +++ b/src/beast/modules/beast_core/thread/Workers.h @@ -134,7 +134,7 @@ private: CPUMeter m_usage; // CPU utilization across threads String m_threadNames; // The name to give each thread WaitableEvent m_allPaused; // signaled when all threads paused - Semaphore m_semaphore; // each pending task is 1 resource + semaphore m_semaphore; // each pending task is 1 resource int m_numberOfThreads; // how many we want active now Atomic m_activeCount; // to know when all are paused Atomic m_pauseCount; // how many threads need to pause now diff --git a/src/beast/modules/beast_crypto/beast_crypto.cpp b/src/beast/modules/beast_crypto/beast_crypto.cpp deleted file mode 100644 index f5ef3ad86f..0000000000 --- a/src/beast/modules/beast_crypto/beast_crypto.cpp +++ /dev/null @@ -1,30 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include "BeastConfig.h" - -#include "beast_crypto.h" - -namespace beast -{ - -#include "math/BinaryEncoding.cpp" -#include "math/UnsignedInteger.cpp" - -} diff --git a/src/beast/modules/beast_crypto/beast_crypto.h b/src/beast/modules/beast_crypto/beast_crypto.h deleted file mode 100644 index 04404475d6..0000000000 --- a/src/beast/modules/beast_crypto/beast_crypto.h +++ /dev/null @@ -1,53 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_BEAST_CRYPTO_H_INCLUDED -#define BEAST_BEAST_CRYPTO_H_INCLUDED - -//------------------------------------------------------------------------------ - -/* If you fail to make sure that all your compile units are building Beast with - the same set of option flags, then there's a risk that different compile - units will treat the classes as having different memory layouts, leading to - very nasty memory corruption errors when they all get linked together. - That's why it's best to always include the BeastConfig.h file before any - beast headers. -*/ -#ifndef BEAST_BEASTCONFIG_H_INCLUDED -# ifdef _MSC_VER -# pragma message ("Have you included your BeastConfig.h file before including the Beast headers?") -# else -# warning "Have you included your BeastConfig.h file before including the Beast headers?" -# endif -#endif - -#include "../beast_core/beast_core.h" -#include "../../beast/crypto/MurmurHash.h" - -//------------------------------------------------------------------------------ - -namespace beast { - -# include "math/UnsignedIntegerCalc.h" -#include "math/UnsignedInteger.h" -#include "math/BinaryEncoding.h" - -} - -#endif diff --git a/src/beast/modules/beast_db/beast_db.cpp b/src/beast/modules/beast_db/beast_db.cpp deleted file mode 100644 index 3cf44b6339..0000000000 --- a/src/beast/modules/beast_db/beast_db.cpp +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include "BeastConfig.h" - -#include "beast_db.h" - -#include "../beast_crypto/beast_crypto.h" - -namespace beast -{ - -#if BEAST_GCC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" -#endif -#include "keyvalue/KeyvaDB.cpp" -#if BEAST_GCC -#pragma GCC diagnostic pop -#endif - -} diff --git a/src/beast/modules/beast_db/beast_db.h b/src/beast/modules/beast_db/beast_db.h deleted file mode 100644 index 575a38d2a2..0000000000 --- a/src/beast/modules/beast_db/beast_db.h +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_BEAST_DB_H_INCLUDED -#define BEAST_BEAST_DB_H_INCLUDED - -//------------------------------------------------------------------------------ - -/* If you fail to make sure that all your compile units are building Beast with - the same set of option flags, then there's a risk that different compile - units will treat the classes as having different memory layouts, leading to - very nasty memory corruption errors when they all get linked together. - That's why it's best to always include the BeastConfig.h file before any - beast headers. -*/ -#ifndef BEAST_BEASTCONFIG_H_INCLUDED -# ifdef _MSC_VER -# pragma message ("Have you included your BeastConfig.h file before including the Beast headers?") -# else -# warning "Have you included your BeastConfig.h file before including the Beast headers?" -# endif -#endif - -#include "../beast_core/beast_core.h" - -//------------------------------------------------------------------------------ - -namespace beast -{ - -#include "keyvalue/KeyvaDB.h" - -} - -#endif diff --git a/src/beast/modules/beast_db/keyvalue/KeyvaDB.cpp b/src/beast/modules/beast_db/keyvalue/KeyvaDB.cpp deleted file mode 100644 index e53ef99732..0000000000 --- a/src/beast/modules/beast_db/keyvalue/KeyvaDB.cpp +++ /dev/null @@ -1,861 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -/* - -TODO - -- Check consistency / range checking on read - -- Cache top level tree nodes - -- Coalesce I/O in RandomAccessFile - -- Delete / file compaction - -*/ - -class KeyvaDBImp : public KeyvaDB -{ -private: - // These are stored in big endian format in the file. - - // A file offset. - typedef int64 FileOffset; - - // Index of a key. - // - // The value is broken up into two parts. The key block index, - // and a 1 based index within the keyblock corresponding to the - // internal key number. - // - typedef int32 KeyIndex; - typedef int32 KeyBlockIndex; - - // Size of a value. - typedef uint32 ByteSize; - -private: - // returns the number of keys in a key block with the specified depth - static int calcKeysAtDepth (int depth) - { - return (1U << depth) - 1; - } - - // returns the number of bytes in a key record - static int calcKeyRecordBytes (int keyBytes) - { - // This depends on the format of a serialized key record - return - sizeof (FileOffset) + - sizeof (ByteSize) + - sizeof (KeyIndex) + - sizeof (KeyIndex) + - keyBytes - ; - } - - // returns the number of bytes in a key block - static int calcKeyBlockBytes (int depth, int keyBytes) - { - return calcKeysAtDepth (depth) * calcKeyRecordBytes (keyBytes); - } - -public: - enum - { - currentVersion = 1 - }; - - - //-------------------------------------------------------------------------- - - struct KeyAddress - { - // 1 based key block number - uint32 blockNumber; - - // 1 based key index within the block, breadth-first left to right - uint32 keyNumber; - }; - - enum - { - // The size of the fixed area at the beginning of the key file. - // This is used to store some housekeeping information like the - // key size and version number. - // - masterHeaderBytes = 1000 - }; - - // The master record is at the beginning of the key file - struct MasterRecord - { - // version number, starting from 1 - int32 version; - - KeyBlockIndex nextKeyBlockIndex; - - void write (OutputStream& stream) - { - stream.writeTypeBigEndian (version); - } - - void read (InputStream& stream) - { - stream.readTypeBigEndianInto (&version); - } - }; - - // Key records are indexed starting at one. - struct KeyRecord : public Uncopyable - { - explicit KeyRecord (void* const keyStorage) - : key (keyStorage) - { - } - - // Absolute byte FileOffset in the value file. - FileOffset valFileOffset; - - // Size of the corresponding value, in bytes. - ByteSize valSize; - - // Key record index of left node, or 0. - KeyIndex leftIndex; - - // Key record index of right node, or 0. - KeyIndex rightIndex; - - // Points to keyBytes storage of the key. - void* const key; - }; - - //-------------------------------------------------------------------------- - - // A complete keyblock. The contents of the memory for the key block - // are identical to the format on disk. Therefore it is necessary to - // use the serialization routines to extract or update the key records. - // - class KeyBlock : public Uncopyable - { - public: - KeyBlock (int depth, int keyBytes) - : m_depth (depth) - , m_keyBytes (keyBytes) - , m_storage (calcKeyBlockBytes (depth, keyBytes)) - { - } - - void read (InputStream& stream) - { - stream.read (m_storage.getData (), calcKeyBlockBytes (m_depth, m_keyBytes)); - } - - void write (OutputStream& stream) - { - stream.write (m_storage.getData (), calcKeyBlockBytes (m_depth, m_keyBytes)); - } - - void readKeyRecord (KeyRecord* keyRecord, int keyIndex) - { - bassert (keyIndex >=1 && keyIndex <= calcKeysAtDepth (m_depth)); - - size_t const byteOffset = (keyIndex - 1) * calcKeyRecordBytes (m_keyBytes); - - MemoryInputStream stream ( - addBytesToPointer (m_storage.getData (), byteOffset), - calcKeyRecordBytes (m_keyBytes), - false); - - stream.readTypeBigEndianInto (&keyRecord->valFileOffset); - stream.readTypeBigEndianInto (&keyRecord->valSize); - stream.readTypeBigEndianInto (&keyRecord->leftIndex); - stream.readTypeBigEndianInto (&keyRecord->rightIndex); - stream.read (keyRecord->key, m_keyBytes); - } - -#if 0 - void writeKeyRecord (KeyRecord const& keyRecord, int keyIndex) - { - bassert (keyIndex >=1 && keyIndex <= calcKeysAtDepth (m_depth)); - -#if 0 - size_t const byteOffset = (keyIndex - 1) * calcKeyRecordBytes (m_keyBytes); - - MemoryOutputStream stream ( - addBytesToPointer (m_storage.getData (), byteOffset), - calcKeyRecordBytes (m_keyBytes)); - - stream.writeTypeBigEndian (keyRecord.valFileOffset); - stream.writeTypeBigEndian (keyRecord.valSize); - stream.writeTypeBigEndian (keyRecord.leftIndex); - stream.writeTypeBigEndian (keyRecord.rightIndex); - stream.write (keyRecord.key, m_keyBytes); -#endif - } -#endif - - private: - int const m_depth; - int const m_keyBytes; - MemoryBlock m_storage; - }; - - //-------------------------------------------------------------------------- - - // Concurrent data - // - struct State - { - RandomAccessFile keyFile; - RandomAccessFile valFile; - MasterRecord masterRecord; - KeyIndex newKeyIndex; - FileOffset valFileSize; - - bool hasKeys () const noexcept - { - return newKeyIndex > 1; - } - }; - - typedef SharedData SharedState; - - //-------------------------------------------------------------------------- - - int const m_keyBytes; - int const m_keyBlockDepth; - SharedState m_state; - HeapBlock m_keyStorage; - - //-------------------------------------------------------------------------- - - KeyvaDBImp (int keyBytes, - int keyBlockDepth, - File keyPath, - File valPath) - : m_keyBytes (keyBytes) - , m_keyBlockDepth (keyBlockDepth) - , m_keyStorage (keyBytes) - { - SharedState::Access state (m_state); - - openFile (&state->keyFile, keyPath); - - int64 const fileSize = state->keyFile.getFile ().getSize (); - - if (fileSize == 0) - { - // VFALCO TODO Better error handling here - // initialize the key file - Result result = state->keyFile.setPosition (masterHeaderBytes - 1); - if (result.wasOk ()) - { - char byte = 0; - - result = state->keyFile.write (&byte, 1); - - if (result.wasOk ()) - { - state->keyFile.flush (); - } - } - } - - state->newKeyIndex = 1 + static_cast ((state->keyFile.getFile ().getSize () - masterHeaderBytes) - / calcKeyRecordBytes (m_keyBytes)); - - openFile (&state->valFile, valPath); - - state->valFileSize = state->valFile.getFile ().getSize (); - } - - ~KeyvaDBImp () - { - SharedState::Access state (m_state); - - flushInternal (state); - } - - // Open a file for reading and writing. - // Creates the file if it doesn't exist. - static void openFile (RandomAccessFile* file, File path) - { - Result const result = file->open (path, RandomAccessFile::readWrite); - - if (! result) - { - String s; - s << "KeyvaDB: Couldn't open " << path.getFileName () << " for writing."; - Throw (std::runtime_error (s.toStdString ())); - } - } - - //-------------------------------------------------------------------------- - - Result createMasterRecord (SharedState::Access& state) - { - MemoryBlock buffer (masterHeaderBytes, true); - - Result result = state->keyFile.setPosition (0); - - if (result.wasOk ()) - { - //MasterRecord mr; - - //mr.version = 1; - - result = state->keyFile.write (buffer.getData (), buffer.getSize ()); - } - - return result; - } - - //-------------------------------------------------------------------------- - - FileOffset calcKeyRecordOffset (KeyIndex keyIndex) - { - bassert (keyIndex > 0); - - FileOffset const byteOffset = masterHeaderBytes + (keyIndex - 1) * calcKeyRecordBytes (m_keyBytes); - - return byteOffset; - } - - // Read a key record into memory. - // VFALCO TODO Return a Result and do validity checking on all inputs - // - void readKeyRecord (KeyRecord* const keyRecord, - KeyIndex const keyIndex, - SharedState::Access& state) - { - FileOffset const byteOffset = calcKeyRecordOffset (keyIndex); - - Result result = state->keyFile.setPosition (byteOffset); - - if (result.wasOk ()) - { - MemoryBlock data (calcKeyRecordBytes (m_keyBytes)); - - size_t bytesRead; - - result = state->keyFile.read (data.getData (), calcKeyRecordBytes (m_keyBytes), &bytesRead); - - if (result.wasOk ()) - { - if (bytesRead == static_cast (calcKeyRecordBytes (m_keyBytes))) - { - MemoryInputStream stream (data, false); - - // This defines the file format! - stream.readTypeBigEndianInto (&keyRecord->valFileOffset); - stream.readTypeBigEndianInto (&keyRecord->valSize); - stream.readTypeBigEndianInto (&keyRecord->leftIndex); - stream.readTypeBigEndianInto (&keyRecord->rightIndex); - - // Grab the key - stream.read (keyRecord->key, m_keyBytes); - } - else - { - result = Result::fail ("KeyvaDB: amountRead != calcKeyRecordBytes()"); - } - } - } - - if (! result.wasOk ()) - { - String s; - s << "KeyvaDB readKeyRecord failed in " << state->keyFile.getFile ().getFileName (); - Throw (std::runtime_error (s.toStdString ())); - } - } - - // Write a key record from memory - void writeKeyRecord (KeyRecord const& keyRecord, - KeyIndex const keyIndex, - SharedState::Access& state, - bool includingKey) - { - FileOffset const byteOffset = calcKeyRecordOffset (keyIndex); - - int const bytes = calcKeyRecordBytes (m_keyBytes) - (includingKey ? 0 : m_keyBytes); - - // VFALCO TODO Recycle this buffer - MemoryBlock data (bytes); - - { - MemoryOutputStream stream (data, false); - - // This defines the file format! - stream.writeTypeBigEndian (keyRecord.valFileOffset); - stream.writeTypeBigEndian (keyRecord.valSize); - stream.writeTypeBigEndian (keyRecord.leftIndex); - stream.writeTypeBigEndian (keyRecord.rightIndex); - - // Write the key - if (includingKey) - stream.write (keyRecord.key, m_keyBytes); - } - - Result result = state->keyFile.setPosition (byteOffset); - - if (result.wasOk ()) - { - size_t bytesWritten; - - result = state->keyFile.write (data.getData (), bytes, &bytesWritten); - - if (result.wasOk ()) - { - if (bytesWritten != static_cast (bytes)) - { - result = Result::fail ("KeyvaDB: bytesWritten != bytes"); - } - } - } - - if (!result.wasOk ()) - { - String s; - s << "KeyvaDB: writeKeyRecord failed in " << state->keyFile.getFile ().getFileName (); - Throw (std::runtime_error (s.toStdString ())); - } - } - - // Append a value to the value file. - // VFALCO TODO return a Result - void writeValue (void const* const value, ByteSize valueBytes, SharedState::Access& state) - { - Result result = state->valFile.setPosition (state->valFileSize); - - if (result.wasOk ()) - { - size_t bytesWritten; - - result = state->valFile.write (value, valueBytes, &bytesWritten); - - if (result.wasOk ()) - { - if (bytesWritten == valueBytes) - { - state->valFileSize += valueBytes; - } - else - { - result = Result::fail ("KeyvaDB: bytesWritten != valueBytes"); - } - } - } - - if (! result.wasOk ()) - { - String s; - s << "KeyvaDB: writeValue failed in " << state->valFile.getFile ().getFileName (); - Throw (std::runtime_error (s.toStdString ())); - } - } - - //-------------------------------------------------------------------------- - - struct FindResult : public Uncopyable - { - FindResult (void* const keyStorage) - : keyRecord (keyStorage) - { - } - - int compare; // result of the last comparison - KeyIndex keyIndex; // index we looked at last - //KeyBlock keyBlock; // KeyBlock we looked at last - KeyRecord keyRecord; // KeyRecord we looked at last - }; - - // Find a key. If the key doesn't exist, enough information - // is left behind in the result to perform an insertion. - // - // Returns true if the key was found. - // - bool find (FindResult* findResult, void const* key, SharedState::Access& state) - { - // Not okay to call this with an empty key file! - bassert (state->hasKeys ()); - - // This performs a standard binary search - - findResult->keyIndex = 1; - - do - { - readKeyRecord (&findResult->keyRecord, findResult->keyIndex, state); - - findResult->compare = memcmp (key, findResult->keyRecord.key, m_keyBytes); - - if (findResult->compare < 0) - { - if (findResult->keyRecord.leftIndex != 0) - { - // Go left - findResult->keyIndex = findResult->keyRecord.leftIndex; - } - else - { - // Insert position is to the left - break; - } - } - else if (findResult->compare > 0) - { - if (findResult->keyRecord.rightIndex != 0) - { - // Go right - findResult->keyIndex = findResult->keyRecord.rightIndex; - } - else - { - // Insert position is to the right - break; - } - } - } - while (findResult->compare != 0); - - return findResult->compare == 0; - } - - //-------------------------------------------------------------------------- - - bool get (void const* key, GetCallback* callback) - { - FindResult findResult (m_keyStorage.getData ()); - - SharedState::Access state (m_state); - - bool found = false; - - if (state->hasKeys ()) - { - found = find (&findResult, key, state); - - if (found) - { - void* const destStorage = callback->getStorageForValue (findResult.keyRecord.valSize); - - Result result = state->valFile.setPosition (findResult.keyRecord.valFileOffset); - - if (result.wasOk ()) - { - size_t bytesRead; - - result = state->valFile.read (destStorage, findResult.keyRecord.valSize, &bytesRead); - - if (result.wasOk ()) - { - if (bytesRead != findResult.keyRecord.valSize) - { - result = Result::fail ("KeyvaDB: bytesRead != valSize"); - } - } - } - - if (! result.wasOk ()) - { - String s; - s << "KeyvaDB: get in " << state->valFile.getFile ().getFileName (); - Throw (std::runtime_error (s.toStdString ())); - } - } - } - - return found; - } - - //-------------------------------------------------------------------------- - - // Write a key value pair. Does nothing if the key exists. - void put (void const* key, void const* value, int valueBytes) - { - bassert (valueBytes > 0); - - SharedState::Access state (m_state); - - if (state->hasKeys ()) - { - // Search for the key - - FindResult findResult (m_keyStorage.getData ()); - - bool const found = find (&findResult, key, state); - - if (! found ) - { - bassert (findResult.compare != 0); - - // Binary tree insertion. - // Link the last key record to the new key - { - if (findResult.compare < 0) - { - findResult.keyRecord.leftIndex = state->newKeyIndex; - } - else - { - findResult.keyRecord.rightIndex = state->newKeyIndex; - } - - writeKeyRecord (findResult.keyRecord, findResult.keyIndex, state, false); - } - - // Write the new key - { - findResult.keyRecord.valFileOffset = state->valFileSize; - findResult.keyRecord.valSize = valueBytes; - findResult.keyRecord.leftIndex = 0; - findResult.keyRecord.rightIndex = 0; - - memcpy (findResult.keyRecord.key, key, m_keyBytes); - - writeKeyRecord (findResult.keyRecord, state->newKeyIndex, state, true); - } - - // Key file has grown by one. - ++state->newKeyIndex; - - // Write the value - writeValue (value, valueBytes, state); - } - else - { - // Key already exists, do nothing. - // We could check to make sure the payloads are the same. - } - } - else - { - // - // Write first key - // - - KeyRecord keyRecord (m_keyStorage.getData ()); - - keyRecord.valFileOffset = state->valFileSize; - keyRecord.valSize = valueBytes; - keyRecord.leftIndex = 0; - keyRecord.rightIndex = 0; - - memcpy (keyRecord.key, key, m_keyBytes); - - writeKeyRecord (keyRecord, state->newKeyIndex, state, true); - - // Key file has grown by one. - ++state->newKeyIndex; - - // - // Write value - // - - bassert (state->valFileSize == 0); - - writeValue (value, valueBytes, state); - } - } - - //-------------------------------------------------------------------------- - - void flush () - { - SharedState::Access state (m_state); - - flushInternal (state); - } - - void flushInternal (SharedState::Access& state) - { - state->keyFile.flush (); - state->valFile.flush (); - } -}; - -KeyvaDB* KeyvaDB::New (int keyBytes, int keyBlockDepth, File keyPath, File valPath) -{ - return new KeyvaDBImp (keyBytes, keyBlockDepth, keyPath, valPath); -} - -//------------------------------------------------------------------------------ - -class KeyvaDBTests : public UnitTest -{ -public: - enum - { - maxPayloadBytes = 8 * 1024 - }; - - // Retrieval callback stores the value in a Payload object for comparison - struct PayloadGetCallback : KeyvaDB::GetCallback - { - UnitTestUtilities::Payload payload; - - PayloadGetCallback () : payload (maxPayloadBytes) - { - } - - void* getStorageForValue (int valueBytes) - { - bassert (valueBytes <= maxPayloadBytes); - - payload.bytes = valueBytes; - - return payload.data.getData (); - } - }; - - KeyvaDB* createDB (unsigned int keyBytes, File const& path) - { - File const keyPath = path.withFileExtension (".key"); - File const valPath = path.withFileExtension (".val"); - - return KeyvaDB::New (keyBytes, 1, keyPath, valPath); - } - - void deleteDBFiles (File const& path) - { - File const keyPath = path.withFileExtension (".key"); - File const valPath = path.withFileExtension (".val"); - - keyPath.deleteFile (); - valPath.deleteFile (); - } - - template - void testKeySize (unsigned int const maxItems) - { - using namespace UnitTestUtilities; - - typedef UnsignedInteger KeyType; - - int64 const seedValue = 50; - - String s; - - s << "keyBytes=" << String (uint64(KeyBytes)) << ", maxItems=" << String (maxItems); - beginTestCase (s); - - // Set up the key and value files - File const path (File::createTempFile ("")); - - { - // open the db - ScopedPointer db (createDB (KeyBytes, path)); - - Payload payload (maxPayloadBytes); - Payload check (maxPayloadBytes); - - { - // Create an array of ascending integers. - HeapBlock items (maxItems); - for (unsigned int i = 0; i < maxItems; ++i) - items [i] = i; - - // Now shuffle it deterministically. - repeatableShuffle (maxItems, items, seedValue); - - // Write all the keys of integers. - for (unsigned int i = 0; i < maxItems; ++i) - { - unsigned int keyIndex = items [i]; - - KeyType const key = KeyType::createFromInteger (keyIndex); - - payload.repeatableRandomFill (1, maxPayloadBytes, keyIndex + seedValue); - - db->put (key.cbegin (), payload.data.getData (), payload.bytes); - - { - // VFALCO TODO Check what we just wrote? - //db->get (key.cbegin (), check.data.getData (), payload.bytes); - } - } - } - - { - // Go through all of our keys and try to retrieve them. - // since this is done in ascending order, we should get - // random seeks at this point. - // - PayloadGetCallback cb; - for (unsigned int keyIndex = 0; keyIndex < maxItems; ++keyIndex) - { - KeyType const v = KeyType::createFromInteger (keyIndex); - - bool const found = db->get (v.cbegin (), &cb); - - expect (found, "Should be found"); - - if (found) - { - payload.repeatableRandomFill (1, maxPayloadBytes, keyIndex + seedValue); - - expect (payload == cb.payload, "Should be equal"); - } - } - } - } - - { - // Re-open the database and confirm the data - ScopedPointer db (createDB (KeyBytes, path)); - - Payload payload (maxPayloadBytes); - Payload check (maxPayloadBytes); - - PayloadGetCallback cb; - for (unsigned int keyIndex = 0; keyIndex < maxItems; ++keyIndex) - { - KeyType const v = KeyType::createFromInteger (keyIndex); - - bool const found = db->get (v.cbegin (), &cb); - - expect (found, "Should be found"); - - if (found) - { - payload.repeatableRandomFill (1, maxPayloadBytes, keyIndex + seedValue); - - expect (payload == cb.payload, "Should be equal"); - } - } - } - - deleteDBFiles (path); - } - - void runTest () - { - testKeySize <4> (500); - testKeySize <32> (4000); - } - - KeyvaDBTests () : UnitTest ("KeyvaDB", "beast", runManual) - { - } -}; - -static KeyvaDBTests keyvaDBTests; diff --git a/src/beast/modules/beast_db/keyvalue/KeyvaDB.h b/src/beast/modules/beast_db/keyvalue/KeyvaDB.h deleted file mode 100644 index 20e4185f49..0000000000 --- a/src/beast/modules/beast_db/keyvalue/KeyvaDB.h +++ /dev/null @@ -1,55 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_KEYVADB_H_INCLUDED -#define BEAST_KEYVADB_H_INCLUDED - -/** Specialized Key/value database - - Once written, a value can never be modified. -*/ -class KeyvaDB : LeakChecked -{ -public: - class GetCallback - { - public: - virtual void* getStorageForValue (int valueBytes) = 0; - }; - - static KeyvaDB* New (int keyBytes, - int keyBlockDepth, - File keyPath, - File valPath); - - virtual ~KeyvaDB () { } - - // VFALCO TODO Make the return value a Result so we can - // detect corruption and errors! - // - virtual bool get (void const* key, GetCallback* callback) = 0; - - // VFALCO TODO Use Result for return value - // - virtual void put (void const* key, void const* value, int valueBytes) = 0; - - virtual void flush () = 0; -}; - -#endif diff --git a/src/beast/modules/beast_extras/beast_extras.cpp b/src/beast/modules/beast_extras/beast_extras.cpp deleted file mode 100644 index 2813fee75f..0000000000 --- a/src/beast/modules/beast_extras/beast_extras.cpp +++ /dev/null @@ -1,29 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include "BeastConfig.h" - -#include "beast_extras.h" - -namespace beast -{ - - - -} diff --git a/src/beast/modules/beast_extras/beast_extras.h b/src/beast/modules/beast_extras/beast_extras.h deleted file mode 100644 index df5d8858b5..0000000000 --- a/src/beast/modules/beast_extras/beast_extras.h +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_EXTRAS_H_INCLUDED -#define BEAST_EXTRAS_H_INCLUDED - -// Adds boost-specific features to beast. - -#include - -// lockable_traits was added in 1.53.0 -#ifndef BEAST_BOOST_HAS_LOCKABLES -# if BOOST_VERSION >= 105300 -# define BEAST_BOOST_HAS_LOCKABLES 1 -# else -# define BEAST_BOOST_HAS_LOCKABLES 0 -# endif -#endif -#if BEAST_BOOST_HAS_LOCKABLES -# include -#endif - -#if BEAST_BOOST_HAS_LOCKABLES -# include "traits/BoostLockableTraits.h" -#endif - -#endif diff --git a/src/beast/modules/beast_extras/traits/BoostLockableTraits.h b/src/beast/modules/beast_extras/traits/BoostLockableTraits.h deleted file mode 100644 index 7e9803b510..0000000000 --- a/src/beast/modules/beast_extras/traits/BoostLockableTraits.h +++ /dev/null @@ -1,125 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_BOOSTLOCKABLERAITS_H_INCLUDED -#define BEAST_BOOSTLOCKABLERAITS_H_INCLUDED - -// Adds beast specializations for boost lockables. - -// beast forward declarations - -namespace beast -{ - -class CriticalSection; - -template -class TrackedMutex; - -template -class UntrackedMutex; - -} - -//------------------------------------------------------------------------------ - -// boost Mutex concepts -// -// http://www.boost.org/doc/libs/1_54_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_concepts - -namespace boost -{ - -namespace sync -{ - -//------------------------------------------------------------------------------ -// -// CriticalSection -// - -// BasicLockable -// -template <> -struct is_basic_lockable - : public boost::true_type { }; - -// Lockable -// -template <> -struct is_lockable - : public boost::true_type { }; - -// RecursiveLockable -// -template <> -struct is_recursive_mutex_sur_parole - : public boost::true_type { }; - -//------------------------------------------------------------------------------ -// -// TrackedMutex <> -// - -// BasicLockable -// -template -class is_basic_lockable > - : public boost::sync::is_basic_lockable { }; - -// Lockable -// -template -class is_lockable > - : public boost::sync::is_lockable { }; - -// RecursiveLockable -// -template -struct is_recursive_mutex_sur_parole > - : public boost::true_type { }; - -//------------------------------------------------------------------------------ -// -// UntrackedMutex <> -// - -// BasicLockable -// -template -class is_basic_lockable > - : public boost::sync::is_basic_lockable { }; - -// Lockable -// -template -class is_lockable > - : public boost::sync::is_lockable { }; - -// RecursiveLockable -// -template -struct is_recursive_mutex_sur_parole > - : public boost::true_type { }; - -} - -} - -#endif diff --git a/src/ripple/beast/ripple_beast.cpp b/src/ripple/beast/ripple_beast.cpp index f12de1462b..17443c0a85 100644 --- a/src/ripple/beast/ripple_beast.cpp +++ b/src/ripple/beast/ripple_beast.cpp @@ -34,8 +34,6 @@ #endif #include "../beast/modules/beast_asio/beast_asio.cpp" -#include "../beast/modules/beast_crypto/beast_crypto.cpp" -#include "../beast/modules/beast_db/beast_db.cpp" #include "../beast/modules/beast_sqdb/beast_sqdb.cpp" #include "../beast/beast/asio/Asio.cpp" diff --git a/src/ripple/http/api/Server.h b/src/ripple/http/api/Server.h index 4f7dccf0e4..f4c8b6a66c 100644 --- a/src/ripple/http/api/Server.h +++ b/src/ripple/http/api/Server.h @@ -20,6 +20,7 @@ #ifndef RIPPLE_HTTP_SERVER_H_INCLUDED #define RIPPLE_HTTP_SERVER_H_INCLUDED +#include #include namespace ripple { @@ -74,7 +75,7 @@ public: void stop (); private: - ScopedPointer m_impl; + std::unique_ptr m_impl; }; } diff --git a/src/ripple/http/impl/Peer.h b/src/ripple/http/impl/Peer.h index b18745b3db..40e1ebe389 100644 --- a/src/ripple/http/impl/Peer.h +++ b/src/ripple/http/impl/Peer.h @@ -20,6 +20,8 @@ #ifndef RIPPLE_HTTP_PEER_H_INCLUDED #define RIPPLE_HTTP_PEER_H_INCLUDED +#include + namespace ripple { namespace HTTP { @@ -57,16 +59,16 @@ public: boost::asio::io_service::strand m_strand; boost::asio::deadline_timer m_data_timer; boost::asio::deadline_timer m_request_timer; - ScopedPointer m_socket; + std::unique_ptr m_socket; MemoryBlock m_buffer; HTTPRequestParser m_parser; int m_writesPending; bool m_closed; bool m_callClose; - Atomic m_detached; SharedPtr m_detach_ref; boost::optional m_work; int m_errorCode; + std::atomic m_detached; //-------------------------------------------------------------------------- @@ -80,6 +82,7 @@ public: , m_closed (false) , m_callClose (false) , m_errorCode (0) + , m_detached (0) { tag = nullptr; @@ -93,7 +96,8 @@ public: case Port::require_ssl: flags = MultiSocket::server_ssl_required; break; } - m_socket = MultiSocket::New (m_impl.get_io_service(), port.context->get(), flags); + m_socket.reset (MultiSocket::New ( + m_impl.get_io_service(), port.context->get(), flags)); m_impl.add (*this); } @@ -163,7 +167,7 @@ public: // Make the Session asynchronous void detach () { - if (m_detached.compareAndSetBool (1, 0)) + if (m_detached.exchange (1) == 0) { bassert (! m_work); bassert (m_detach_ref.empty()); diff --git a/src/ripple/peerfinder/impl/CheckerAdapter.h b/src/ripple/peerfinder/impl/CheckerAdapter.h index 3972ff6b31..392684c5cf 100644 --- a/src/ripple/peerfinder/impl/CheckerAdapter.h +++ b/src/ripple/peerfinder/impl/CheckerAdapter.h @@ -20,6 +20,8 @@ #ifndef RIPPLE_PEERFINDER_CHECKERADAPTER_H_INCLUDED #define RIPPLE_PEERFINDER_CHECKERADAPTER_H_INCLUDED +#include + namespace ripple { namespace PeerFinder { @@ -39,7 +41,7 @@ class CheckerAdapter : public Checker private: SerializedContext& m_context; ServiceQueue& m_queue; - ScopedPointer m_checker; + std::unique_ptr m_checker; struct Handler { diff --git a/src/ripple/sitefiles/impl/Logic.h b/src/ripple/sitefiles/impl/Logic.h index 69bc28e3d2..dac872e48b 100644 --- a/src/ripple/sitefiles/impl/Logic.h +++ b/src/ripple/sitefiles/impl/Logic.h @@ -20,6 +20,8 @@ #ifndef RIPPLE_SITEFILES_LOGIC_H_INCLUDED #define RIPPLE_SITEFILES_LOGIC_H_INCLUDED +#include + namespace ripple { namespace SiteFiles { @@ -74,7 +76,7 @@ public: SharedState m_state; Journal m_journal; - ScopedPointer m_client; + std::unique_ptr m_client; explicit Logic (Journal journal) : m_journal (journal) diff --git a/src/ripple/testoverlay/api/NetworkType.h b/src/ripple/testoverlay/api/NetworkType.h index 13138bbd2e..8d712fa588 100644 --- a/src/ripple/testoverlay/api/NetworkType.h +++ b/src/ripple/testoverlay/api/NetworkType.h @@ -20,8 +20,7 @@ #ifndef RIPPLE_TESTOVERLAY_NETWORKTYPE_H_INCLUDED #define RIPPLE_TESTOVERLAY_NETWORKTYPE_H_INCLUDED -namespace TestOverlay -{ +namespace TestOverlay { template class NetworkType : public ConfigParam @@ -33,7 +32,7 @@ public: typedef typename Config::State State; typedef typename Config::SizeType SizeType; - typedef std::vector > Peers; + typedef std::vector > Peers; NetworkType () : m_steps (0) @@ -63,7 +62,7 @@ public: Peer& createPeer () { Peer* peer (new Peer (*this)); - m_peers.push_back (peer); + m_peers.push_back (std::unique_ptr (peer)); return *peer; } diff --git a/src/ripple/testoverlay/ripple_testoverlay.h b/src/ripple/testoverlay/ripple_testoverlay.h index f2d622326c..3c2058da27 100644 --- a/src/ripple/testoverlay/ripple_testoverlay.h +++ b/src/ripple/testoverlay/ripple_testoverlay.h @@ -25,6 +25,8 @@ #include "beast/modules/beast_core/beast_core.h" +#include + /** Provides a template based peer to peer network simulator. A TestOverlay::Network simulates an entire peer to peer network. diff --git a/src/ripple/types/api/Base58.h b/src/ripple/types/api/Base58.h index fa737bc530..5fafe245b6 100644 --- a/src/ripple/types/api/Base58.h +++ b/src/ripple/types/api/Base58.h @@ -33,6 +33,7 @@ #define RIPPLE_TYPES_BASE58_H #include +#include #include "Blob.h" @@ -87,7 +88,7 @@ public: Alphabet const& alphabet, bool withCheck) { typedef typename std::iterator_traits::value_type value_type; - std::vector ::type> v; + std::vector ::type> v; std::size_t const size (std::distance (first, last)); if (withCheck) { diff --git a/src/ripple/types/api/RippleAssets.h b/src/ripple/types/api/RippleAssets.h index 82799675ed..f62448d0b8 100644 --- a/src/ripple/types/api/RippleAssets.h +++ b/src/ripple/types/api/RippleAssets.h @@ -20,15 +20,7 @@ #ifndef RIPPLE_TYPES_RIPPLEASSETS_H_INCLUDED #define RIPPLE_TYPES_RIPPLEASSETS_H_INCLUDED -#ifndef RIPPLE_USE_C11 -#define RIPPLE_USE_C11 1 -#endif - -#if RIPPLE_USE_C11 -# include -#else -# include "beast/beast/mpl/IfCond.h" -#endif +#include namespace ripple { @@ -55,21 +47,12 @@ template class RippleAssetType { public: -#if RIPPLE_USE_C11 typedef typename std::conditional ::type Currency; typedef typename std::conditional ::type Issuer; -#else - typedef typename mpl::IfCond ::type Currency; - - typedef typename mpl::IfCond ::type Issuer; -#endif - Currency currency; Issuer issuer; diff --git a/src/ripple/types/ripple_types.h b/src/ripple/types/ripple_types.h index fc64bda250..b53d2b068d 100644 --- a/src/ripple/types/ripple_types.h +++ b/src/ripple/types/ripple_types.h @@ -23,7 +23,7 @@ #include "../json/ripple_json.h" #include "beast/modules/beast_core/beast_core.h" -#include "beast/modules/beast_crypto/beast_crypto.h" // for UnsignedInteger, Remove ASAP! +#include "beast/beast/Crypto.h" #include "beast/modules/beast_core/system/BeforeBoost.h" #include diff --git a/src/ripple/validators/impl/Logic.h b/src/ripple/validators/impl/Logic.h index 23ce75bca7..dabdff6bbc 100644 --- a/src/ripple/validators/impl/Logic.h +++ b/src/ripple/validators/impl/Logic.h @@ -20,6 +20,8 @@ #ifndef RIPPLE_VALIDATORS_LOGIC_H_INCLUDED #define RIPPLE_VALIDATORS_LOGIC_H_INCLUDED +#include + namespace ripple { namespace Validators { @@ -158,7 +160,7 @@ public: { if (findSourceByID (source->uniqueID())) { - ScopedPointer object (source); + std::unique_ptr object (source); m_journal.error << "Duplicate " << source->name(); return; } diff --git a/src/ripple/validators/impl/SourceFile.cpp b/src/ripple/validators/impl/SourceFile.cpp index a0811536f8..7da64eb286 100644 --- a/src/ripple/validators/impl/SourceFile.cpp +++ b/src/ripple/validators/impl/SourceFile.cpp @@ -89,10 +89,7 @@ private: SourceFile* SourceFile::New (File const& file) { - ScopedPointer object ( - new SourceFileImp (file)); - - return object.release (); + return new SourceFileImp (file); } } diff --git a/src/ripple/validators/impl/SourceStrings.cpp b/src/ripple/validators/impl/SourceStrings.cpp index 171062c9bb..d128f3998d 100644 --- a/src/ripple/validators/impl/SourceStrings.cpp +++ b/src/ripple/validators/impl/SourceStrings.cpp @@ -75,10 +75,7 @@ private: SourceStrings* SourceStrings::New ( String name, StringArray const& strings) { - ScopedPointer object ( - new SourceStringsImp (name, strings)); - - return object.release (); + return new SourceStringsImp (name, strings); } } diff --git a/src/ripple/validators/impl/SourceURL.cpp b/src/ripple/validators/impl/SourceURL.cpp index b414e6cd05..7bca13961b 100644 --- a/src/ripple/validators/impl/SourceURL.cpp +++ b/src/ripple/validators/impl/SourceURL.cpp @@ -17,6 +17,8 @@ */ //============================================================================== +#include + namespace ripple { namespace Validators { @@ -75,7 +77,7 @@ public: private: URL m_url; - ScopedPointer m_client; + std::unique_ptr m_client; }; //------------------------------------------------------------------------------ diff --git a/src/ripple_app/consensus/LedgerConsensus.cpp b/src/ripple_app/consensus/LedgerConsensus.cpp index 436c558b95..7f54d2a811 100644 --- a/src/ripple_app/consensus/LedgerConsensus.cpp +++ b/src/ripple_app/consensus/LedgerConsensus.cpp @@ -556,14 +556,14 @@ public: if (mState != lcsFINISHED) return; - fallthru (); + // Fall through case lcsFINISHED: stateFinished (); if (mState != lcsACCEPTED) return; - fallthru (); + // Fall through case lcsACCEPTED: stateAccepted (); diff --git a/src/ripple_app/data/Database.h b/src/ripple_app/data/Database.h index ba092b4787..80de4d83a8 100644 --- a/src/ripple_app/data/Database.h +++ b/src/ripple_app/data/Database.h @@ -90,6 +90,7 @@ public: // float getSingleDBValueFloat(const char* sql); // char* getSingleDBValueStr(const char* sql, std::string& retStr); + // VFALCO TODO Make this parameter a reference instead of a pointer. virtual bool setupCheckpointing (JobQueue*) { return false; diff --git a/src/ripple_app/ledger/InboundLedger.cpp b/src/ripple_app/ledger/InboundLedger.cpp index 0254d42596..8a8a529d71 100644 --- a/src/ripple_app/ledger/InboundLedger.cpp +++ b/src/ripple_app/ledger/InboundLedger.cpp @@ -267,7 +267,7 @@ boost::weak_ptr InboundLedger::pmDowncast () static void LADispatch ( Job& job, InboundLedger::pointer la, - std::vector< FUNCTION_TYPE > trig) + std::vector< std::function > trig) { if (la->isComplete() && !la->isFailed()) { @@ -290,7 +290,7 @@ void InboundLedger::done () assert (isComplete () || isFailed ()); - std::vector< FUNCTION_TYPE > triggers; + std::vector< std::function > triggers; { ScopedLockType sl (mLock, __FILE__, __LINE__); triggers.swap (mOnComplete); @@ -310,7 +310,7 @@ void InboundLedger::done () BIND_TYPE (LADispatch, P_1, shared_from_this (), triggers)); } -bool InboundLedger::addOnComplete (FUNCTION_TYPE triggerFunc) +bool InboundLedger::addOnComplete (std::function triggerFunc) { ScopedLockType sl (mLock, __FILE__, __LINE__); diff --git a/src/ripple_app/ledger/InboundLedger.h b/src/ripple_app/ledger/InboundLedger.h index 7605b7bd84..0b02b4bda9 100644 --- a/src/ripple_app/ledger/InboundLedger.h +++ b/src/ripple_app/ledger/InboundLedger.h @@ -68,7 +68,7 @@ public: } // VFALCO TODO Make this the Listener / Observer pattern - bool addOnComplete (FUNCTION_TYPE); + bool addOnComplete (std::function); void trigger (Peer::ref); bool tryLocal (); @@ -129,7 +129,7 @@ private: std::vector mReceivedData; bool mReceiveDispatched; - std::vector > mOnComplete; + std::vector > mOnComplete; }; #endif diff --git a/src/ripple_app/ledger/Ledger.cpp b/src/ripple_app/ledger/Ledger.cpp index fd3faecba5..5620a3a33c 100644 --- a/src/ripple_app/ledger/Ledger.cpp +++ b/src/ripple_app/ledger/Ledger.cpp @@ -1206,7 +1206,7 @@ SLE::pointer Ledger::getSLEi (uint256 const& uId) return ret; } -void Ledger::visitAccountItems (const uint160& accountID, FUNCTION_TYPE func) +void Ledger::visitAccountItems (const uint160& accountID, std::function func) { // Visit each item in this account's owner directory uint256 rootIndex = Ledger::getOwnerDirIndex (accountID); @@ -1234,12 +1234,12 @@ void Ledger::visitAccountItems (const uint160& accountID, FUNCTION_TYPE& function, SHAMapItem::ref item) +static void visitHelper (std::function& function, SHAMapItem::ref item) { function (boost::make_shared (item->peekSerializer (), item->getTag ())); } -void Ledger::visitStateItems (FUNCTION_TYPE function) +void Ledger::visitStateItems (std::function function) { try { diff --git a/src/ripple_app/ledger/Ledger.h b/src/ripple_app/ledger/Ledger.h index 1c6cc3f520..c782117392 100644 --- a/src/ripple_app/ledger/Ledger.h +++ b/src/ripple_app/ledger/Ledger.h @@ -264,8 +264,8 @@ public: SLE::pointer getAccountRoot (const uint160 & accountID); SLE::pointer getAccountRoot (const RippleAddress & naAccountID); void updateSkipList (); - void visitAccountItems (const uint160 & acctID, FUNCTION_TYPE); - void visitStateItems (FUNCTION_TYPE); + void visitAccountItems (const uint160 & acctID, std::function); + void visitStateItems (std::function); // database functions (low-level) static Ledger::pointer loadByIndex (uint32 ledgerIndex); diff --git a/src/ripple_app/ledger/LedgerEntrySet.cpp b/src/ripple_app/ledger/LedgerEntrySet.cpp index 06a578a90e..741bcdd18a 100644 --- a/src/ripple_app/ledger/LedgerEntrySet.cpp +++ b/src/ripple_app/ledger/LedgerEntrySet.cpp @@ -213,7 +213,8 @@ void LedgerEntrySet::entryModify (SLE::ref sle) { case taaCACHED: it->second.mAction = taaMODIFY; - fallthru (); + + // Fall through case taaCREATE: case taaMODIFY: @@ -641,7 +642,7 @@ TER LedgerEntrySet::dirAdd ( uint64& uNodeDir, uint256 const& uRootIndex, uint256 const& uLedgerIndex, - FUNCTION_TYPE fDescriber) + std::function fDescriber) { WriteLog (lsTRACE, LedgerEntrySet) << boost::str (boost::format ("dirAdd: uRootIndex=%s uLedgerIndex=%s") % uRootIndex.ToString () diff --git a/src/ripple_app/ledger/LedgerEntrySet.h b/src/ripple_app/ledger/LedgerEntrySet.h index 145bef8386..b75b67fe0b 100644 --- a/src/ripple_app/ledger/LedgerEntrySet.h +++ b/src/ripple_app/ledger/LedgerEntrySet.h @@ -160,7 +160,7 @@ public: uint64 & uNodeDir, // Node of entry. uint256 const & uRootIndex, uint256 const & uLedgerIndex, - FUNCTION_TYPE fDescriber); + std::function fDescriber); TER dirDelete ( const bool bKeepRoot, diff --git a/src/ripple_app/ledger/LedgerMaster.cpp b/src/ripple_app/ledger/LedgerMaster.cpp index 4b1adfc4e1..3df3bbba71 100644 --- a/src/ripple_app/ledger/LedgerMaster.cpp +++ b/src/ripple_app/ledger/LedgerMaster.cpp @@ -30,7 +30,7 @@ class LedgerMasterImp , public LeakChecked { public: - typedef FUNCTION_TYPE callback; + typedef std::function callback; typedef RippleRecursiveMutex LockType; typedef LockType::ScopedLockType ScopedLockType; @@ -38,7 +38,7 @@ public: Journal m_journal; - LockType mLock; + LockType m_mutex; TransactionEngine mEngine; @@ -49,11 +49,6 @@ public: Ledger::pointer mPubLedger; // The last ledger we have published Ledger::pointer mPathLedger; // The last ledger we did pathfinding against - beast::Atomic mPubLedgerClose; - beast::Atomic mPubLedgerSeq; - beast::Atomic mValidLedgerClose; - beast::Atomic mValidLedgerSeq; - LedgerHistory mLedgerHistory; CanonicalTXSet mHeldTransactions; @@ -61,7 +56,7 @@ public: LockType mCompleteLock; RangeSet mCompleteLedgers; - ScopedPointer mLedgerCleaner; + std::unique_ptr mLedgerCleaner; int mMinValidations; // The minimum validations to publish a ledger uint256 mLastValidateHash; @@ -77,16 +72,17 @@ public: bool mPathFindNewLedger; bool mPathFindNewRequest; + std::atomic mPubLedgerClose; + std::atomic mPubLedgerSeq; + std::atomic mValidLedgerClose; + std::atomic mValidLedgerSeq; + //-------------------------------------------------------------------------- explicit LedgerMasterImp (Stoppable& parent, Journal journal) : LedgerMaster (parent) , m_journal (journal) - , mLock (this, "LedgerMaster", __FILE__, __LINE__) - , mPubLedgerClose (0) - , mPubLedgerSeq (0) - , mValidLedgerClose (0) - , mValidLedgerSeq (0) + , m_mutex (this, "LedgerMaster", __FILE__, __LINE__) , mHeldTransactions (uint256 ()) , mLedgerCleaner (LedgerCleaner::New(*this, LogPartition::getJournal())) , mMinValidations (0) @@ -96,6 +92,10 @@ public: , mFillInProgress (0) , mPathFindThread (false) , mPathFindNewRequest (false) + , mPubLedgerClose (0) + , mPubLedgerSeq (0) + , mValidLedgerClose (0) + , mValidLedgerSeq (0) { } @@ -120,7 +120,7 @@ public: int getPublishedLedgerAge () { - uint32 pubClose = mPubLedgerClose.get(); + uint32 pubClose = mPubLedgerClose.load(); if (!pubClose) { WriteLog (lsDEBUG, LedgerMaster) << "No published ledger"; @@ -137,7 +137,7 @@ public: int getValidatedLedgerAge () { - uint32 valClose = mValidLedgerClose.get(); + uint32 valClose = mValidLedgerClose.load(); if (!valClose) { WriteLog (lsDEBUG, LedgerMaster) << "No validated ledger"; @@ -159,8 +159,8 @@ public: reason = "No recently-published ledger"; return false; } - uint32 validClose = mValidLedgerClose.get(); - uint32 pubClose = mPubLedgerClose.get(); + uint32 validClose = mValidLedgerClose.load(); + uint32 pubClose = mPubLedgerClose.load(); if (!validClose || !pubClose) { reason = "No published ledger"; @@ -191,7 +191,7 @@ public: void addHeldTransaction (Transaction::ref transaction) { // returns true if transaction was added - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); mHeldTransactions.push_back (transaction->getSTransaction ()); } @@ -202,7 +202,7 @@ public: WriteLog (lsINFO, LedgerMaster) << "PushLedger: " << newLedger->getHash (); { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); if (mClosedLedger) { @@ -231,7 +231,7 @@ public: { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); mClosedLedger = newLCL; mCurrentLedger = newOL; mEngine.setLedger (newOL); @@ -254,7 +254,7 @@ public: assert (lastClosed && current); { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); mClosedLedger = lastClosed; mClosedLedger->setClosed (); mClosedLedger->setAccepted (); @@ -284,7 +284,7 @@ public: Ledger::pointer closeLedger (bool recover) { - ScopedLockType sl (mLock, __FILE__, __LINE__); + ScopedLockType sl (m_mutex, __FILE__, __LINE__); Ledger::pointer closingLedger = mCurrentLedger; if (recover) @@ -331,7 +331,7 @@ public: TER result; { - ScopedLockType sl (mLock, __FILE__, __LINE__); + ScopedLockType sl (m_mutex, __FILE__, __LINE__); result = mEngine.applyTransaction (*txn, params, didApply); ledger = mEngine.getLedger (); } @@ -362,7 +362,7 @@ public: // returns Ledgers we have all the nodes for bool getFullValidatedRange (uint32& minVal, uint32& maxVal) { - maxVal = mPubLedgerSeq.get(); + maxVal = mPubLedgerSeq.load(); if (!maxVal) return false; @@ -383,7 +383,7 @@ public: // Returns Ledgers we have all the nodes for and are indexed bool getValidatedRange (uint32& minVal, uint32& maxVal) { - maxVal = mPubLedgerSeq.get(); + maxVal = mPubLedgerSeq.load(); if (!maxVal) return false; @@ -445,7 +445,7 @@ public: while (! job.shouldCancel() && seq > 0) { { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); minHas = seq; --seq; @@ -483,7 +483,7 @@ public: mCompleteLedgers.setRange (minHas, maxHas); } { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); mFillInProgress = 0; tryAdvance(); } @@ -582,7 +582,7 @@ public: mCompleteLedgers.setValue (ledger->getLedgerSeq ()); } - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); if (!mValidLedger || (ledger->getLedgerSeq() > mValidLedger->getLedgerSeq())) setValidLedger(ledger); @@ -643,11 +643,11 @@ public: void checkAccept (Ledger::ref ledger) { - if (ledger->getLedgerSeq() <= mValidLedgerSeq.get()) + if (ledger->getLedgerSeq() <= mValidLedgerSeq.load()) return; // Can we advance the last fully-validated ledger? If so, can we publish? - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); if (mValidLedger && (ledger->getLedgerSeq() <= mValidLedger->getLedgerSeq ())) return; @@ -704,7 +704,7 @@ public: void advanceThread() { - ScopedLockType sl (mLock, __FILE__, __LINE__); + ScopedLockType sl (m_mutex, __FILE__, __LINE__); assert (mValidLedger && mAdvanceThread); WriteLog (lsTRACE, LedgerMaster) << "advanceThread<"; @@ -749,7 +749,7 @@ public: { WriteLog (lsTRACE, LedgerMaster) << "advanceThread should acquire"; { - ScopedUnlockType sl(mLock, __FILE__, __LINE__); + ScopedUnlockType sl(m_mutex, __FILE__, __LINE__); Ledger::pointer nextLedger = mLedgerHistory.getLedgerBySeq(missing + 1); if (nextLedger) { @@ -782,7 +782,7 @@ public: setFullLedger(ledger, false, false); if ((mFillInProgress == 0) && (Ledger::getHashByIndex(ledger->getLedgerSeq() - 1) == ledger->getParentHash())) { // Previous ledger is in DB - ScopedLockType sl(mLock, __FILE__, __LINE__); + ScopedLockType sl(m_mutex, __FILE__, __LINE__); mFillInProgress = ledger->getLedgerSeq(); getApp().getJobQueue().addJob(jtADVANCE, "tryFill", BIND_TYPE ( &LedgerMasterImp::tryFill, this, P_1, ledger)); @@ -832,7 +832,7 @@ public: BOOST_FOREACH(Ledger::ref ledger, pubLedgers) { { - ScopedUnlockType sul (mLock, __FILE__, __LINE__); + ScopedUnlockType sul (m_mutex, __FILE__, __LINE__); WriteLog(lsDEBUG, LedgerMaster) << "tryAdvance publishing seq " << ledger->getLedgerSeq(); setFullLedger(ledger, true, true); @@ -883,7 +883,7 @@ public: uint32 valSeq = mValidLedger->getLedgerSeq(); Ledger::pointer valLedger = mValidLedger; - ScopedUnlockType sul(mLock, __FILE__, __LINE__); + ScopedUnlockType sul(m_mutex, __FILE__, __LINE__); try { for (uint32 seq = pubSeq; seq <= valSeq; ++seq) @@ -956,7 +956,7 @@ public: void tryAdvance() { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); // Can't advance without at least one fully-valid ledger mAdvanceWork = true; @@ -1004,7 +1004,7 @@ public: if (getApp().getOPs().isNeedNetworkLedger ()) { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); mPathFindThread = false; return; } @@ -1015,7 +1015,7 @@ public: bool hasNew = mPathFindNewRequest; { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); if (!mPathLedger || (mPathLedger->getLedgerSeq() < mValidLedger->getLedgerSeq())) { // We have a new valid ledger since the last full pathfinding @@ -1052,7 +1052,7 @@ public: void newPathRequest () { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); mPathFindNewRequest = true; if (!mPathFindThread) @@ -1066,7 +1066,7 @@ public: // If the order book is radically updated, we need to reprocess all pathfinding requests void newOrderBookDB () { - ScopedLockType ml (mLock, __FILE__, __LINE__); + ScopedLockType ml (m_mutex, __FILE__, __LINE__); mPathLedger.reset(); if (!mPathFindThread) @@ -1079,7 +1079,7 @@ public: LockType& peekMutex () { - return mLock; + return m_mutex; } // The current ledger is the ledger we believe new transactions should go in @@ -1153,7 +1153,7 @@ public: Ledger::pointer referenceLedger; { - ScopedLockType sl (mLock, __FILE__, __LINE__); + ScopedLockType sl (m_mutex, __FILE__, __LINE__); referenceLedger = mValidLedger; } if (referenceLedger) @@ -1200,7 +1200,7 @@ public: Ledger::pointer getLedgerBySeq (uint32 index) { { - ScopedLockType sl (mLock, __FILE__, __LINE__); + ScopedLockType sl (m_mutex, __FILE__, __LINE__); if (mCurrentLedger && (mCurrentLedger->getLedgerSeq () == index)) return mCurrentLedger; diff --git a/src/ripple_app/ledger/LedgerMaster.h b/src/ripple_app/ledger/LedgerMaster.h index 05a3c89be0..308faef5b0 100644 --- a/src/ripple_app/ledger/LedgerMaster.h +++ b/src/ripple_app/ledger/LedgerMaster.h @@ -34,7 +34,7 @@ protected: explicit LedgerMaster (Stoppable& parent); public: - typedef FUNCTION_TYPE callback; + typedef std::function callback; public: typedef RippleRecursiveMutex LockType; diff --git a/src/ripple_app/main/Application.cpp b/src/ripple_app/main/Application.cpp index 4f29f1ab09..9009b9bc91 100644 --- a/src/ripple_app/main/Application.cpp +++ b/src/ripple_app/main/Application.cpp @@ -321,19 +321,19 @@ public: DatabaseCon* getRpcDB () { - return mRpcDB; + return mRpcDB.get(); } DatabaseCon* getTxnDB () { - return mTxnDB; + return mTxnDB.get(); } DatabaseCon* getLedgerDB () { - return mLedgerDB; + return mLedgerDB.get(); } DatabaseCon* getWalletDB () { - return mWalletDB; + return mWalletDB.get(); } bool isShutdown () @@ -354,10 +354,10 @@ public: { switch (index) { - case 0: mRpcDB = openDatabaseCon ("rpc.db", RpcDBInit, RpcDBCount); break; - case 1: mTxnDB = openDatabaseCon ("transaction.db", TxnDBInit, TxnDBCount); break; - case 2: mLedgerDB = openDatabaseCon ("ledger.db", LedgerDBInit, LedgerDBCount); break; - case 3: mWalletDB = openDatabaseCon ("wallet.db", WalletDBInit, WalletDBCount); break; + case 0: mRpcDB.reset (openDatabaseCon ("rpc.db", RpcDBInit, RpcDBCount)); break; + case 1: mTxnDB.reset (openDatabaseCon ("transaction.db", TxnDBInit, TxnDBCount)); break; + case 2: mLedgerDB.reset (openDatabaseCon ("ledger.db", LedgerDBInit, LedgerDBCount)); break; + case 3: mWalletDB.reset (openDatabaseCon ("wallet.db", WalletDBInit, WalletDBCount)); break; }; } @@ -427,8 +427,8 @@ public: getApp().getTxnDB ()->getDB ()->executeSQL (boost::str (boost::format ("PRAGMA cache_size=-%d;") % (getConfig ().getSize (siTxnDBCache) * 1024))); - mTxnDB->getDB ()->setupCheckpointing (m_jobQueue); - mLedgerDB->getDB ()->setupCheckpointing (m_jobQueue); + mTxnDB->getDB ()->setupCheckpointing (m_jobQueue.get()); + mLedgerDB->getDB ()->setupCheckpointing (m_jobQueue.get()); if (!getConfig ().RUN_STANDALONE) updateTables (); @@ -495,8 +495,8 @@ public: // SSL context used for Peer connections. { - m_peerSSLContext = RippleSSLContext::createAnonymous ( - getConfig ().PEER_SSL_CIPHER_LIST); + m_peerSSLContext.reset (RippleSSLContext::createAnonymous ( + getConfig ().PEER_SSL_CIPHER_LIST)); // VFALCO NOTE, It seems the WebSocket context never has // set_verify_mode called, for either setting of WEBSOCKET_SECURE @@ -508,8 +508,8 @@ public: // the creation of the peer SSL context and Peers object into // the conditional. // - m_peers = add (Peers::New (m_mainIoPool, *m_resourceManager, *m_siteFiles, - m_mainIoPool, m_peerSSLContext->get ())); + m_peers.reset (add (Peers::New (m_mainIoPool, *m_resourceManager, *m_siteFiles, + m_mainIoPool, m_peerSSLContext->get ()))); // If we're not in standalone mode, // prepare ourselves for networking @@ -548,24 +548,24 @@ public: // SSL context used for WebSocket connections. if (getConfig ().WEBSOCKET_SECURE) { - m_wsSSLContext = RippleSSLContext::createAuthenticated ( + m_wsSSLContext.reset (RippleSSLContext::createAuthenticated ( getConfig ().WEBSOCKET_SSL_KEY, getConfig ().WEBSOCKET_SSL_CERT, - getConfig ().WEBSOCKET_SSL_CHAIN); + getConfig ().WEBSOCKET_SSL_CHAIN)); } else { - m_wsSSLContext = RippleSSLContext::createWebSocket (); + m_wsSSLContext.reset (RippleSSLContext::createWebSocket ()); } // Create private listening WebSocket socket // if (!getConfig ().WEBSOCKET_IP.empty () && getConfig ().WEBSOCKET_PORT) { - m_wsPrivateDoor = WSDoor::New (*m_resourceManager, + m_wsPrivateDoor.reset (WSDoor::New (*m_resourceManager, getOPs(), getConfig ().WEBSOCKET_IP, getConfig ().WEBSOCKET_PORT, false, false, - m_wsSSLContext->get ()); + m_wsSSLContext->get ())); if (m_wsPrivateDoor == nullptr) { @@ -582,10 +582,10 @@ public: // if (!getConfig ().WEBSOCKET_PUBLIC_IP.empty () && getConfig ().WEBSOCKET_PUBLIC_PORT) { - m_wsPublicDoor = WSDoor::New (*m_resourceManager, + m_wsPublicDoor.reset (WSDoor::New (*m_resourceManager, getOPs(), getConfig ().WEBSOCKET_PUBLIC_IP, getConfig ().WEBSOCKET_PUBLIC_PORT, true, false, - m_wsSSLContext->get ()); + m_wsSSLContext->get ())); if (m_wsPublicDoor == nullptr) { @@ -599,10 +599,10 @@ public: } if (!getConfig ().WEBSOCKET_PROXY_IP.empty () && getConfig ().WEBSOCKET_PROXY_PORT) { - m_wsProxyDoor = WSDoor::New (*m_resourceManager, + m_wsProxyDoor.reset (WSDoor::New (*m_resourceManager, getOPs(), getConfig ().WEBSOCKET_PROXY_IP, getConfig ().WEBSOCKET_PROXY_PORT, true, true, - m_wsSSLContext->get ()); + m_wsSSLContext->get ())); if (m_wsProxyDoor == nullptr) { @@ -626,7 +626,7 @@ public: { try { - m_rpcDoor = RPCDoor::New (m_mainIoPool, m_rpcServerHandler); + m_rpcDoor.reset (RPCDoor::New (m_mainIoPool, m_rpcServerHandler)); } catch (const std::exception& e) { @@ -896,51 +896,52 @@ private: LocalCredentials m_localCredentials; TransactionMaster m_txMaster; - beast::unique_ptr m_collectorManager; - ScopedPointer m_resourceManager; - ScopedPointer m_rpcServiceManager; + std::unique_ptr m_collectorManager; + std::unique_ptr m_resourceManager; + std::unique_ptr m_rpcServiceManager; // These are Stoppable-related - ScopedPointer m_jobQueue; + std::unique_ptr m_jobQueue; IoServicePool m_mainIoPool; - ScopedPointer m_siteFiles; + std::unique_ptr m_siteFiles; + // VFALCO TODO Make OrderBookDB abstract OrderBookDB m_orderBookDB; - ScopedPointer m_ledgerMaster; - ScopedPointer m_networkOPs; - ScopedPointer m_deprecatedUNL; - ScopedPointer m_rpcHTTPServer; + std::unique_ptr m_ledgerMaster; + std::unique_ptr m_networkOPs; + std::unique_ptr m_deprecatedUNL; + std::unique_ptr m_rpcHTTPServer; #if ! RIPPLE_USE_RPC_SERVICE_MANAGER RPCServerHandler m_rpcServerHandler; #endif NodeStoreScheduler m_nodeStoreScheduler; - ScopedPointer m_nodeStore; - ScopedPointer m_sntpClient; - beast::unique_ptr m_inboundLedgers; - ScopedPointer m_txQueue; - ScopedPointer m_validators; - ScopedPointer mFeatures; - ScopedPointer mFeeVote; - ScopedPointer mFeeTrack; - ScopedPointer mHashRouter; - ScopedPointer mValidations; - ScopedPointer mProofOfWorkFactory; - ScopedPointer m_loadManager; + std::unique_ptr m_nodeStore; + std::unique_ptr m_sntpClient; + std::unique_ptr m_inboundLedgers; + std::unique_ptr m_txQueue; + std::unique_ptr m_validators; + std::unique_ptr mFeatures; + std::unique_ptr mFeeVote; + std::unique_ptr mFeeTrack; + std::unique_ptr mHashRouter; + std::unique_ptr mValidations; + std::unique_ptr mProofOfWorkFactory; + std::unique_ptr m_loadManager; DeadlineTimer m_sweepTimer; bool volatile mShutdown; - ScopedPointer mRpcDB; - ScopedPointer mTxnDB; - ScopedPointer mLedgerDB; - ScopedPointer mWalletDB; + std::unique_ptr mRpcDB; + std::unique_ptr mTxnDB; + std::unique_ptr mLedgerDB; + std::unique_ptr mWalletDB; - ScopedPointer m_peerSSLContext; - ScopedPointer m_wsSSLContext; - ScopedPointer m_peers; + std::unique_ptr m_peerSSLContext; + std::unique_ptr m_wsSSLContext; + std::unique_ptr m_peers; OwnedArray m_peerDoors; - ScopedPointer m_rpcDoor; - ScopedPointer m_wsPublicDoor; - ScopedPointer m_wsPrivateDoor; - ScopedPointer m_wsProxyDoor; + std::unique_ptr m_rpcDoor; + std::unique_ptr m_wsPublicDoor; + std::unique_ptr m_wsPrivateDoor; + std::unique_ptr m_wsProxyDoor; WaitableEvent m_stop; }; @@ -1246,7 +1247,7 @@ void ApplicationImp::updateTables () if (getConfig ().doImport) { NodeStore::DummyScheduler scheduler; - ScopedPointer source (NodeStore::Database::New ( + std::unique_ptr source (NodeStore::Database::New ( "NodeStore.import", scheduler, LogPartition::getJournal (), getConfig ().importNodeDatabase)); diff --git a/src/ripple_app/main/CollectorManager.cpp b/src/ripple_app/main/CollectorManager.cpp index 3115c8be7a..57b0d05807 100644 --- a/src/ripple_app/main/CollectorManager.cpp +++ b/src/ripple_app/main/CollectorManager.cpp @@ -24,7 +24,7 @@ class CollectorManagerImp { public: Journal m_journal; - shared_ptr m_collector; + std::shared_ptr m_collector; CollectorManagerImp (StringPairArray const& params, Journal journal) @@ -50,7 +50,7 @@ public: { } - shared_ptr const& collector () + std::shared_ptr const& collector () { return m_collector; } diff --git a/src/ripple_app/main/CollectorManager.h b/src/ripple_app/main/CollectorManager.h index 82ce026c54..9285db52f8 100644 --- a/src/ripple_app/main/CollectorManager.h +++ b/src/ripple_app/main/CollectorManager.h @@ -31,7 +31,7 @@ public: static CollectorManager* New (StringPairArray const& params, Journal journal); virtual ~CollectorManager () = 0; - virtual shared_ptr const& collector () = 0; + virtual std::shared_ptr const& collector () = 0; }; } diff --git a/src/ripple_app/main/NodeStoreScheduler.h b/src/ripple_app/main/NodeStoreScheduler.h index e2bf48e305..75a40ddd63 100644 --- a/src/ripple_app/main/NodeStoreScheduler.h +++ b/src/ripple_app/main/NodeStoreScheduler.h @@ -36,7 +36,7 @@ private: void doTask (NodeStore::Task& task, Job&); JobQueue& m_jobQueue; - Atomic m_taskCount; + std::atomic m_taskCount; }; diff --git a/src/ripple_app/main/RPCHTTPServer.cpp b/src/ripple_app/main/RPCHTTPServer.cpp index 8b3bbf5c51..1f96f74804 100644 --- a/src/ripple_app/main/RPCHTTPServer.cpp +++ b/src/ripple_app/main/RPCHTTPServer.cpp @@ -29,7 +29,7 @@ public: NetworkOPs& m_networkOPs; RPCServerHandler m_deprecatedHandler; HTTP::Server m_server; - ScopedPointer m_context; + std::unique_ptr m_context; RPCHTTPServerImp (Stoppable& parent, Journal journal, @@ -46,14 +46,14 @@ public: { if (getConfig ().RPC_SECURE == 0) { - m_context = RippleSSLContext::createBare (); + m_context.reset (RippleSSLContext::createBare ()); } else { - m_context = RippleSSLContext::createAuthenticated ( + m_context.reset (RippleSSLContext::createAuthenticated ( getConfig ().RPC_SSL_KEY, getConfig ().RPC_SSL_CERT, - getConfig ().RPC_SSL_CHAIN); + getConfig ().RPC_SSL_CHAIN)); } } @@ -76,7 +76,7 @@ public: port.port = getConfig ().getRpcPort(); else port.port = ep.port(); - port.context = m_context; + port.context = m_context.get (); HTTP::Ports ports; ports.push_back (port); diff --git a/src/ripple_app/main/RippleMain.cpp b/src/ripple_app/main/RippleMain.cpp index cff95bf785..944dc85a7c 100644 --- a/src/ripple_app/main/RippleMain.cpp +++ b/src/ripple_app/main/RippleMain.cpp @@ -154,7 +154,7 @@ public: // code demands the Application object exists. // // TODO To find out who, just comment the next line out - m_app = Application::New (); + m_app.reset (Application::New ()); setAssertOnFailure (false); } @@ -195,7 +195,7 @@ private: private: bool const m_shouldLog; - ScopedPointer m_app; + std::unique_ptr m_app; }; static int runUnitTests (String const& match, String const& format) @@ -455,7 +455,7 @@ int RippleMain::run (int argc, char const* const* argv) if (!vm.count ("parameters")) { // No arguments. Run server. - ScopedPointer app (Application::New ()); + std::unique_ptr app (Application::New ()); setupServer (); startServer (); } diff --git a/src/ripple_app/misc/NetworkOPs.cpp b/src/ripple_app/misc/NetworkOPs.cpp index f7f7d5526d..990d08306e 100644 --- a/src/ripple_app/misc/NetworkOPs.cpp +++ b/src/ripple_app/misc/NetworkOPs.cpp @@ -147,7 +147,7 @@ public: // // Transaction operations // - typedef FUNCTION_TYPE stCallback; // must complete immediately + typedef std::function stCallback; // must complete immediately void submitTransaction (Job&, SerializedTransaction::pointer, stCallback callback = stCallback ()); Transaction::pointer submitTransactionSync (Transaction::ref tpTrans, bool bAdmin, bool bFailHard, bool bSubmit); @@ -1778,12 +1778,8 @@ NetworkOPsImp::getAccountTxs (const RippleAddress& account, int32 minLedger, int TransactionMetaSet::pointer meta = boost::make_shared (txn->getID (), txn->getLedger (), rawMeta.getData ()); -#ifdef C11X + // VFALCO NOTE Use emplace instead. ret.push_back (std::pair (txn, meta)); -#else - ret.push_back (std::pair (txn, meta)); -#endif - } } @@ -1937,11 +1933,7 @@ NetworkOPsImp::getTxsAccount (const RippleAddress& account, int32 minLedger, int --numberOfResults; TransactionMetaSet::pointer meta = boost::make_shared (txn->getID (), txn->getLedger (), rawMeta.getData ()); -#ifdef C11X ret.push_back (std::pair (txn, meta)); -#else - ret.push_back (std::pair (txn, meta)); -#endif } } } @@ -3008,7 +3000,8 @@ void NetworkOPsImp::makeFetchPack (Job&, boost::weak_ptr wPeer, if (reply.objects ().size () >= 256) break; - haveLedger = MOVE_P(wantLedger); + // VFALCO NOTE Why use move? + haveLedger = std::move (wantLedger); wantLedger = getLedgerByHash (haveLedger->getParentHash ()); } while (wantLedger && (UptimeTimer::getInstance ().getElapsedSeconds () <= (uUptime + 1))); @@ -3101,7 +3094,5 @@ NetworkOPs::NetworkOPs (Stoppable& parent) NetworkOPs* NetworkOPs::New (LedgerMaster& ledgerMaster, Stoppable& parent, Journal journal) { - ScopedPointer object (new NetworkOPsImp ( - ledgerMaster, parent, journal)); - return object.release (); + return new NetworkOPsImp (ledgerMaster, parent, journal); } diff --git a/src/ripple_app/misc/NetworkOPs.h b/src/ripple_app/misc/NetworkOPs.h index f69eefc280..b2c0d5aacc 100644 --- a/src/ripple_app/misc/NetworkOPs.h +++ b/src/ripple_app/misc/NetworkOPs.h @@ -136,7 +136,7 @@ public: // must complete immediately // VFALCO TODO Make this a TxCallback structure - typedef FUNCTION_TYPE stCallback; + typedef std::function stCallback; virtual void submitTransaction (Job&, SerializedTransaction::pointer, stCallback callback = stCallback ()) = 0; virtual Transaction::pointer submitTransactionSync (Transaction::ref tpTrans, diff --git a/src/ripple_app/misc/ProofOfWorkFactory.cpp b/src/ripple_app/misc/ProofOfWorkFactory.cpp index 00bf249d3a..97d94881e5 100644 --- a/src/ripple_app/misc/ProofOfWorkFactory.cpp +++ b/src/ripple_app/misc/ProofOfWorkFactory.cpp @@ -349,8 +349,7 @@ private: ProofOfWorkFactory* ProofOfWorkFactory::New () { - ScopedPointer object (new ProofOfWorkFactoryImp); - return object.release (); + return new ProofOfWorkFactoryImp; } //------------------------------------------------------------------------------ diff --git a/src/ripple_app/misc/SerializedTransaction.cpp b/src/ripple_app/misc/SerializedTransaction.cpp index 5eb9de6239..3f4dfc95d4 100644 --- a/src/ripple_app/misc/SerializedTransaction.cpp +++ b/src/ripple_app/misc/SerializedTransaction.cpp @@ -344,7 +344,7 @@ public: pass (); } - UPTR_T new_obj = STObject::parseJson (j.getJson (0), sfGeneric); + std::unique_ptr new_obj = STObject::parseJson (j.getJson (0), sfGeneric); if (new_obj.get () == NULL) fail ("Unable to build object from json"); diff --git a/src/ripple_app/node/SqliteFactory.cpp b/src/ripple_app/node/SqliteFactory.cpp index 4667838e94..202abde123 100644 --- a/src/ripple_app/node/SqliteFactory.cpp +++ b/src/ripple_app/node/SqliteFactory.cpp @@ -218,7 +218,7 @@ public: private: size_t const m_keyBytes; std::string const m_name; - ScopedPointer m_db; + std::unique_ptr m_db; NodeStore::Scheduler& m_scheduler; }; diff --git a/src/ripple_app/paths/PathRequest.cpp b/src/ripple_app/paths/PathRequest.cpp index c5c79d5140..54554ffa69 100644 --- a/src/ripple_app/paths/PathRequest.cpp +++ b/src/ripple_app/paths/PathRequest.cpp @@ -23,7 +23,7 @@ SETUP_LOG (PathRequest) PathRequest::StaticLockType PathRequest::sLock ("PathRequest", __FILE__, __LINE__); std::set PathRequest::sRequests; RippleLineCache::pointer PathRequest::sLineCache; -Atomic PathRequest::siLastIdentifier(0); +std::atomic PathRequest::s_last_id (0); PathRequest::PathRequest (const boost::shared_ptr& subscriber) : mLock (this, "PathRequest", __FILE__, __LINE__) @@ -33,7 +33,7 @@ PathRequest::PathRequest (const boost::shared_ptr& subscriber) , bNew (true) , iLastLevel (0) , bLastSuccess (false) - , iIdentifier (++siLastIdentifier) + , iIdentifier (++s_last_id) { WriteLog (lsINFO, PathRequest) << iIdentifier << " created"; } @@ -504,5 +504,3 @@ void PathRequest::updateAll (Ledger::ref inLedger, bool newOnly, bool hasNew, Ca WriteLog (lsDEBUG, PathRequest) << "updateAll complete " << processed << " process and " << removed << " removed"; } - -// vim:ts=4 diff --git a/src/ripple_app/paths/PathRequest.h b/src/ripple_app/paths/PathRequest.h index 881cc048fd..cb1ce726ff 100644 --- a/src/ripple_app/paths/PathRequest.h +++ b/src/ripple_app/paths/PathRequest.h @@ -89,7 +89,8 @@ private: bool bLastSuccess; int iIdentifier; - static Atomic siLastIdentifier; + + static std::atomic s_last_id; // Track all requests static std::set sRequests; diff --git a/src/ripple_app/paths/Pathfinder.cpp b/src/ripple_app/paths/Pathfinder.cpp index 80b277a70c..85efcd5f46 100644 --- a/src/ripple_app/paths/Pathfinder.cpp +++ b/src/ripple_app/paths/Pathfinder.cpp @@ -450,14 +450,13 @@ bool Pathfinder::matchesOrigin (const uint160& currency, const uint160& issuer) return (issuer == mSrcIssuerID) || (issuer == mSrcAccountID); } +// VFALCO TODO Use RippleCurrency, RippleAccount, et. al. in argument list here int Pathfinder::getPathsOut (RippleCurrency const& currencyID, const uint160& accountID, bool isDstCurrency, const uint160& dstAccount) { -#ifdef C11X + // VFALCO TODO Use RippleAsset here std::pair accountCurrency (currencyID, accountID); -#else - std::pair accountCurrency (currencyID, accountID); -#endif + // VFALCO TODO Use RippleAsset here boost::unordered_map, int>::iterator it = mPOMap.find (accountCurrency); if (it != mPOMap.end ()) diff --git a/src/ripple_app/peers/NameResolver.h b/src/ripple_app/peers/NameResolver.h index c5f32c3152..0860e0a524 100644 --- a/src/ripple_app/peers/NameResolver.h +++ b/src/ripple_app/peers/NameResolver.h @@ -20,12 +20,14 @@ #ifndef RIPPLE_PEER_NAMERESOLVER_H_INCLUDED #define RIPPLE_PEER_NAMERESOLVER_H_INCLUDED +#include + namespace ripple { class NameResolver { public: - typedef boost::function < + typedef std::function < void (std::string, std::vector, boost::system::error_code)> HandlerType; diff --git a/src/ripple_app/peers/Peer.cpp b/src/ripple_app/peers/Peer.cpp index b085bb41b0..3d6418dfe8 100644 --- a/src/ripple_app/peers/Peer.cpp +++ b/src/ripple_app/peers/Peer.cpp @@ -41,7 +41,7 @@ private: public: - ScopedPointer m_socket; + std::unique_ptr m_socket; boost::asio::io_service::strand m_strand; NativeSocketType& getNativeSocket () diff --git a/src/ripple_app/peers/Peers.cpp b/src/ripple_app/peers/Peers.cpp index 30a5e78a30..cf33affad0 100644 --- a/src/ripple_app/peers/Peers.cpp +++ b/src/ripple_app/peers/Peers.cpp @@ -64,7 +64,7 @@ public: typedef boost::unordered_map::value_type vtConMap; Resource::Manager& m_resourceManager; - ScopedPointer m_peerFinder; + std::unique_ptr m_peerFinder; boost::asio::io_service& m_io_service; boost::asio::ssl::context& m_ssl_context; @@ -107,7 +107,7 @@ public: Peer::pointer peerConnect (const std::string& strIp, int iPort); - ScopedPointer m_resolver; + std::unique_ptr m_resolver; //-------------------------------------------------------------------------- diff --git a/src/ripple_app/rpc/RPCHandler.cpp b/src/ripple_app/rpc/RPCHandler.cpp index 6b9f7daa13..c71b35f012 100644 --- a/src/ripple_app/rpc/RPCHandler.cpp +++ b/src/ripple_app/rpc/RPCHandler.cpp @@ -276,7 +276,7 @@ Json::Value RPCHandler::transactionSign (Json::Value params, bool bSubmit, bool return rpcError (rpcSRC_ACT_NOT_FOUND); } - UPTR_T sopTrans; + std::unique_ptr sopTrans; try { @@ -989,7 +989,7 @@ Json::Value RPCHandler::doProofCreate (Json::Value params, Resource::Charge& loa if (params.isMember ("difficulty") || params.isMember ("secret")) { // VFALCO TODO why aren't we using the app's factory? - beast::ScopedPointer pgGen (ProofOfWorkFactory::New ()); + std::unique_ptr pgGen (ProofOfWorkFactory::New ()); if (params.isMember ("difficulty")) { @@ -1075,7 +1075,7 @@ Json::Value RPCHandler::doProofVerify (Json::Value params, Resource::Charge& loa if (params.isMember ("difficulty") || params.isMember ("secret")) { // VFALCO TODO why aren't we using the app's factory? - beast::ScopedPointer pgGen (ProofOfWorkFactory::New ()); + std::unique_ptr pgGen (ProofOfWorkFactory::New ()); if (params.isMember ("difficulty")) { diff --git a/src/ripple_app/shamap/SHAMap.h b/src/ripple_app/shamap/SHAMap.h index fb857732b8..0eac5e8f46 100644 --- a/src/ripple_app/shamap/SHAMap.h +++ b/src/ripple_app/shamap/SHAMap.h @@ -34,7 +34,7 @@ class SHAMap { private: /** Function object which handles missing nodes. */ - typedef beast::function MissingNodeHandler; + typedef std::function MissingNodeHandler; /** Default handler which calls NetworkOPs. */ struct DefaultMissingNodeHandler @@ -126,7 +126,7 @@ public: SHAMapItem::pointer peekNextItem (uint256 const& ); SHAMapItem::pointer peekNextItem (uint256 const& , SHAMapTreeNode::TNType & type); SHAMapItem::pointer peekPrevItem (uint256 const& ); - void visitLeaves(FUNCTION_TYPE); + void visitLeaves(std::function); // comparison/sync functions void getMissingNodes (std::vector& nodeIDs, std::vector& hashes, int max, @@ -216,7 +216,7 @@ public: typedef std::pair fetchPackEntry_t; std::list getFetchPack (SHAMap * have, bool includeLeaves, int max); - void getFetchPack (SHAMap * have, bool includeLeaves, int max, FUNCTION_TYPE); + void getFetchPack (SHAMap * have, bool includeLeaves, int max, std::function); // tree node cache operations static SHAMapTreeNode::pointer getCache (uint256 const& hash, SHAMapNode const& id); @@ -274,7 +274,7 @@ private: bool walkBranch (SHAMapTreeNode * node, SHAMapItem::ref otherMapItem, bool isFirstMap, Delta & differences, int & maxCount); - void visitLeavesInternal (FUNCTION_TYPE& function); + void visitLeavesInternal (std::function& function); private: #if 1 diff --git a/src/ripple_app/shamap/SHAMapSync.cpp b/src/ripple_app/shamap/SHAMapSync.cpp index db64ff6cb0..bf637e1bac 100644 --- a/src/ripple_app/shamap/SHAMapSync.cpp +++ b/src/ripple_app/shamap/SHAMapSync.cpp @@ -23,7 +23,7 @@ static const uint256 uZero; KeyCache SHAMap::fullBelowCache ("fullBelowCache", 524288, 240); -void SHAMap::visitLeaves (FUNCTION_TYPE function) +void SHAMap::visitLeaves (std::function function) { SHAMap::pointer snap; { @@ -33,7 +33,7 @@ void SHAMap::visitLeaves (FUNCTION_TYPE function) snap->visitLeavesInternal(function); } -void SHAMap::visitLeavesInternal (FUNCTION_TYPE& function) +void SHAMap::visitLeavesInternal (std::function& function) { assert (root->isValid ()); @@ -532,15 +532,16 @@ std::list SHAMap::getFetchPack (SHAMap* have, bool inc } void SHAMap::getFetchPack (SHAMap* have, bool includeLeaves, int max, - FUNCTION_TYPE func) + std::function func) { ScopedLockType ul1 (mLock, __FILE__, __LINE__); - ScopedPointer ul2; + std::unique_ptr ul2; if (have) { - ul2 = new LockType::ScopedTryLockType (have->mLock, __FILE__, __LINE__); + // VFALCO NOTE This looks like a mess. A dynamically allocated scoped lock? + ul2.reset (new LockType::ScopedTryLockType (have->mLock, __FILE__, __LINE__)); if (! ul2->owns_lock ()) { diff --git a/src/ripple_app/tx/TransactionEngine.cpp b/src/ripple_app/tx/TransactionEngine.cpp index 195dbfd2b4..fd05673e1b 100644 --- a/src/ripple_app/tx/TransactionEngine.cpp +++ b/src/ripple_app/tx/TransactionEngine.cpp @@ -99,7 +99,7 @@ TER TransactionEngine::applyTransaction (const SerializedTransaction& txn, Trans #endif - UPTR_T transactor = Transactor::makeTransactor (txn, params, this); + std::unique_ptr transactor = Transactor::makeTransactor (txn, params, this); if (transactor.get () != NULL) { diff --git a/src/ripple_app/tx/TransactionMeta.cpp b/src/ripple_app/tx/TransactionMeta.cpp index 3d43ba23e3..e680ccefdd 100644 --- a/src/ripple_app/tx/TransactionMeta.cpp +++ b/src/ripple_app/tx/TransactionMeta.cpp @@ -27,7 +27,7 @@ TransactionMetaSet::TransactionMetaSet (uint256 const& txid, uint32 ledger, Blob Serializer s (vec); SerializerIterator sit (s); - UPTR_T pobj = STObject::deserialize (sit, sfAffectedNodes); + std::unique_ptr pobj = STObject::deserialize (sit, sfAffectedNodes); STObject* obj = static_cast (pobj.get ()); if (!obj) diff --git a/src/ripple_app/tx/Transactor.cpp b/src/ripple_app/tx/Transactor.cpp index 325bb2a243..ae68a7ddcd 100644 --- a/src/ripple_app/tx/Transactor.cpp +++ b/src/ripple_app/tx/Transactor.cpp @@ -19,37 +19,37 @@ SETUP_LOG (Transactor) -UPTR_T Transactor::makeTransactor (const SerializedTransaction& txn, TransactionEngineParams params, TransactionEngine* engine) +std::unique_ptr Transactor::makeTransactor (const SerializedTransaction& txn, TransactionEngineParams params, TransactionEngine* engine) { switch (txn.getTxnType ()) { case ttPAYMENT: - return UPTR_T (new PaymentTransactor (txn, params, engine)); + return std::unique_ptr (new PaymentTransactor (txn, params, engine)); case ttACCOUNT_SET: - return UPTR_T (new AccountSetTransactor (txn, params, engine)); + return std::unique_ptr (new AccountSetTransactor (txn, params, engine)); case ttREGULAR_KEY_SET: - return UPTR_T (new RegularKeySetTransactor (txn, params, engine)); + return std::unique_ptr (new RegularKeySetTransactor (txn, params, engine)); case ttTRUST_SET: - return UPTR_T (new TrustSetTransactor (txn, params, engine)); + return std::unique_ptr (new TrustSetTransactor (txn, params, engine)); case ttOFFER_CREATE: - return UPTR_T (new OfferCreateTransactor (txn, params, engine)); + return std::unique_ptr (new OfferCreateTransactor (txn, params, engine)); case ttOFFER_CANCEL: - return UPTR_T (new OfferCancelTransactor (txn, params, engine)); + return std::unique_ptr (new OfferCancelTransactor (txn, params, engine)); case ttWALLET_ADD: - return UPTR_T (new WalletAddTransactor (txn, params, engine)); + return std::unique_ptr (new WalletAddTransactor (txn, params, engine)); case ttFEATURE: case ttFEE: - return UPTR_T (new ChangeTransactor (txn, params, engine)); + return std::unique_ptr (new ChangeTransactor (txn, params, engine)); default: - return UPTR_T (); + return std::unique_ptr (); } } diff --git a/src/ripple_app/tx/Transactor.h b/src/ripple_app/tx/Transactor.h index 97f77e9c91..c85bf6a466 100644 --- a/src/ripple_app/tx/Transactor.h +++ b/src/ripple_app/tx/Transactor.h @@ -25,7 +25,7 @@ class Transactor public: typedef boost::shared_ptr pointer; - static UPTR_T makeTransactor (const SerializedTransaction& txn, TransactionEngineParams params, TransactionEngine* engine); + static std::unique_ptr makeTransactor (const SerializedTransaction& txn, TransactionEngineParams params, TransactionEngine* engine); TER apply (); diff --git a/src/ripple_app/tx/TxQueue.cpp b/src/ripple_app/tx/TxQueue.cpp index 9dde3931c0..45aa08b521 100644 --- a/src/ripple_app/tx/TxQueue.cpp +++ b/src/ripple_app/tx/TxQueue.cpp @@ -139,6 +139,5 @@ private: TxQueue* TxQueue::New () { - ScopedPointer object (new TxQueueImp); - return object.release (); + return new TxQueueImp; } diff --git a/src/ripple_app/tx/TxQueueEntry.h b/src/ripple_app/tx/TxQueueEntry.h index 11fe377ee8..86f6973fc3 100644 --- a/src/ripple_app/tx/TxQueueEntry.h +++ b/src/ripple_app/tx/TxQueueEntry.h @@ -26,7 +26,7 @@ class TxQueueEntry public: typedef boost::shared_ptr pointer; typedef const boost::shared_ptr& ref; - typedef FUNCTION_TYPE stCallback; // must complete immediately + typedef std::function stCallback; // must complete immediately public: TxQueueEntry (Transaction::ref tx, bool sigChecked) : mTxn (tx), mSigChecked (sigChecked) diff --git a/src/ripple_basics/ripple_basics.h b/src/ripple_basics/ripple_basics.h index 80827c5c74..9991b89058 100644 --- a/src/ripple_basics/ripple_basics.h +++ b/src/ripple_basics/ripple_basics.h @@ -21,13 +21,15 @@ #define RIPPLE_BASICS_H_INCLUDED #include "beast/modules/beast_core/beast_core.h" -#include "beast/modules/beast_crypto/beast_crypto.h" +#include "beast/beast/Crypto.h" #include "beast/modules/beast_core/system/BeforeBoost.h" #include "system/BoostIncludes.h" #include "../../beast/beast/Utility.h" +#include + #ifndef RIPPLE_TRACK_MUTEXES # define RIPPLE_TRACK_MUTEXES 0 #endif diff --git a/src/ripple_basics/utility/CountedObject.cpp b/src/ripple_basics/utility/CountedObject.cpp index 2aec1ae25b..bc86cbccba 100644 --- a/src/ripple_basics/utility/CountedObject.cpp +++ b/src/ripple_basics/utility/CountedObject.cpp @@ -25,6 +25,8 @@ CountedObjects& CountedObjects::getInstance () } CountedObjects::CountedObjects () + : m_count (0) + , m_head (nullptr) { } @@ -38,11 +40,11 @@ CountedObjects::List CountedObjects::getCounts (int minimumThreshold) const // When other operations are concurrent, the count // might be temporarily less than the actual count. - int const count = m_count.get (); + int const count = m_count.load (); counts.reserve (count); - CounterBase* counter = m_head.get (); + CounterBase* counter = m_head.load (); while (counter != nullptr) { @@ -65,6 +67,7 @@ CountedObjects::List CountedObjects::getCounts (int minimumThreshold) const //------------------------------------------------------------------------------ CountedObjects::CounterBase::CounterBase () + : m_count (0) { // Insert ourselves at the front of the lock-free linked list @@ -73,10 +76,10 @@ CountedObjects::CounterBase::CounterBase () do { - head = instance.m_head.get (); + head = instance.m_head.load (); m_next = head; } - while (! instance.m_head.compareAndSetBool (this, head)); + while (instance.m_head.exchange (this) != head); ++instance.m_count; } @@ -87,5 +90,3 @@ CountedObjects::CounterBase::~CounterBase () // undefined behavior will result if the singleton's member // functions are called. } - -//------------------------------------------------------------------------------ diff --git a/src/ripple_basics/utility/CountedObject.h b/src/ripple_basics/utility/CountedObject.h index 052d65cf92..e71e56b7ef 100644 --- a/src/ripple_basics/utility/CountedObject.h +++ b/src/ripple_basics/utility/CountedObject.h @@ -46,22 +46,22 @@ public: virtual ~CounterBase (); - inline int increment () noexcept + int increment () noexcept { return ++m_count; } - inline int decrement () noexcept + int decrement () noexcept { return --m_count; } - inline int getCount () const noexcept + int getCount () const noexcept { - return m_count.get (); + return m_count.load (); } - inline CounterBase* getNext () const noexcept + CounterBase* getNext () const noexcept { return m_next; } @@ -72,18 +72,17 @@ public: virtual void checkPureVirtual () const = 0; protected: - beast::Atomic m_count; + std::atomic m_count; CounterBase* m_next; }; private: CountedObjects (); - ~CountedObjects (); private: - beast::Atomic m_count; - beast::Atomic m_head; + std::atomic m_count; + std::atomic m_head; }; //------------------------------------------------------------------------------ diff --git a/src/ripple_basics/utility/PlatformMacros.h b/src/ripple_basics/utility/PlatformMacros.h index 507464a54e..8750be3733 100644 --- a/src/ripple_basics/utility/PlatformMacros.h +++ b/src/ripple_basics/utility/PlatformMacros.h @@ -20,33 +20,15 @@ #ifndef RIPPLE_PLATFORMMACROS_H #define RIPPLE_PLATFORMMACROS_H -#define FUNCTION_TYPE beast::function #define BIND_TYPE beast::bind #define P_1 beast::_1 #define P_2 beast::_2 #define P_3 beast::_3 #define P_4 beast::_4 -// VFALCO TODO Clean this up - -#if (!defined(FORCE_NO_C11X) && (__cplusplus > 201100L)) || defined(FORCE_C11X) - -// VFALCO TODO Get rid of the C11X macro -#define C11X -#define UPTR_T std::unique_ptr -#define MOVE_P(p) std::move(p) - -#else - -//#define UPTR_T std::auto_ptr -#define UPTR_T ScopedPointer -#define MOVE_P(p) (p) - -#endif - // VFALCO TODO Clean this stuff up. Remove as much as possible +// DEPRECATED #define nothing() do {} while (0) -#define fallthru() do {} while (0) #define NUMBER(x) (sizeof(x)/sizeof((x)[0])) #define isSetBit(x,y) (!!((x) & (y))) diff --git a/src/ripple_core/functional/Job.cpp b/src/ripple_core/functional/Job.cpp index ba65bb1625..fb1fd4965e 100644 --- a/src/ripple_core/functional/Job.cpp +++ b/src/ripple_core/functional/Job.cpp @@ -43,7 +43,7 @@ Job::Job (JobType type, std::string const& name, uint64 index, LoadMonitor& lm, - FUNCTION_TYPE const& job, + std::function const& job, CancelCallback cancelCallback) : m_cancelCallback (cancelCallback) , mType (type) diff --git a/src/ripple_core/functional/Job.h b/src/ripple_core/functional/Job.h index 02ad3bcafd..b709430be3 100644 --- a/src/ripple_core/functional/Job.h +++ b/src/ripple_core/functional/Job.h @@ -90,7 +90,7 @@ public: std::string const& name, uint64 index, LoadMonitor& lm, - FUNCTION_TYPE const& job, + std::function const& job, CancelCallback cancelCallback); Job& operator= (Job const& other); @@ -118,7 +118,7 @@ private: CancelCallback m_cancelCallback; JobType mType; uint64 mJobIndex; - FUNCTION_TYPE mJob; + std::function mJob; LoadEvent::pointer m_loadEvent; std::string mName; }; diff --git a/src/ripple_core/functional/JobQueue.cpp b/src/ripple_core/functional/JobQueue.cpp index 2bebdac72d..e2e7c06ecb 100644 --- a/src/ripple_core/functional/JobQueue.cpp +++ b/src/ripple_core/functional/JobQueue.cpp @@ -74,7 +74,7 @@ public: //-------------------------------------------------------------------------- - JobQueueImp (shared_ptr const& collector, + JobQueueImp (std::shared_ptr const& collector, Stoppable& parent, Journal journal) : JobQueue ("JobQueue", parent) , m_journal (journal) @@ -83,7 +83,7 @@ public: , m_workers (*this, "JobQueue", 0) , m_cancelCallback (boost::bind (&Stoppable::isStopping, this)) { - m_metrics.hook = collector->make_hook (beast::bind ( + m_metrics.hook = collector->make_hook (std::bind ( &JobQueueImp::collect, this)); m_metrics.job_count = collector->make_gauge ("job_count"); @@ -130,7 +130,7 @@ public: m_metrics.job_count = m_jobSet.size (); } - void addJob (JobType type, const std::string& name, const FUNCTION_TYPE& jobFunc) + void addJob (JobType type, const std::string& name, const std::function& jobFunc) { bassert (type != jtINVALID); @@ -726,7 +726,7 @@ JobQueue::JobQueue (char const* name, Stoppable& parent) //------------------------------------------------------------------------------ -JobQueue* JobQueue::New (shared_ptr const& collector, +JobQueue* JobQueue::New (std::shared_ptr const& collector, Stoppable& parent, Journal journal) { return new JobQueueImp (collector, parent, journal); diff --git a/src/ripple_core/functional/JobQueue.h b/src/ripple_core/functional/JobQueue.h index fd22585d67..e50e90373a 100644 --- a/src/ripple_core/functional/JobQueue.h +++ b/src/ripple_core/functional/JobQueue.h @@ -26,7 +26,7 @@ protected: JobQueue (char const* name, Stoppable& parent); public: - static JobQueue* New (shared_ptr const& collector, + static JobQueue* New (std::shared_ptr const& collector, Stoppable& parent, Journal journal); virtual ~JobQueue () { } @@ -34,7 +34,7 @@ public: // VFALCO TODO make convenience functions that allow the caller to not // have to call bind. // - virtual void addJob (JobType type, const std::string& name, const FUNCTION_TYPE& job) = 0; + virtual void addJob (JobType type, const std::string& name, const std::function& job) = 0; // Jobs waiting at this priority virtual int getJobCount (JobType t) = 0; diff --git a/src/ripple_core/functional/LoadEvent.h b/src/ripple_core/functional/LoadEvent.h index a4c0748e2c..c48313c215 100644 --- a/src/ripple_core/functional/LoadEvent.h +++ b/src/ripple_core/functional/LoadEvent.h @@ -37,7 +37,7 @@ public: // Why both kinds of containers? // typedef boost::shared_ptr pointer; - typedef UPTR_T autoptr; + typedef std::unique_ptr autoptr; public: // VFALCO TODO remove the dependency on LoadMonitor. Is that possible? diff --git a/src/ripple_core/nodestore/NodeStore.cpp b/src/ripple_core/nodestore/NodeStore.cpp index 5ee695a21b..3fddb74b9a 100644 --- a/src/ripple_core/nodestore/NodeStore.cpp +++ b/src/ripple_core/nodestore/NodeStore.cpp @@ -18,7 +18,6 @@ //============================================================================== // backend support -#include "beast/modules/beast_db/beast_db.h" #include "../ripple_hyperleveldb/ripple_hyperleveldb.h" #include "../ripple_leveldb/ripple_leveldb.h" #include "../ripple/rocksdb/ripple_rocksdb.h" @@ -30,8 +29,6 @@ namespace ripple { # include "impl/BatchWriter.h" # include "backend/HyperDBFactory.h" #include "backend/HyperDBFactory.cpp" -# include "backend/KeyvaDBFactory.h" -#include "backend/KeyvaDBFactory.cpp" # include "backend/LevelDBFactory.h" #include "backend/LevelDBFactory.cpp" # include "backend/MemoryFactory.h" diff --git a/src/ripple_core/nodestore/api/Database.h b/src/ripple_core/nodestore/api/Database.h index 041fd84acf..83fac08bfd 100644 --- a/src/ripple_core/nodestore/api/Database.h +++ b/src/ripple_core/nodestore/api/Database.h @@ -46,7 +46,7 @@ public: backends also require a 'path' field. Some choices for 'type' are: - HyperLevelDB, LevelDBFactory, SQLite, KeyvaDB, MDB + HyperLevelDB, LevelDBFactory, SQLite, MDB If the fastBackendParameter is omitted or empty, no ephemeral database is used. If the scheduler parameter is omited or unspecified, a diff --git a/src/ripple_core/nodestore/backend/HyperDBFactory.cpp b/src/ripple_core/nodestore/backend/HyperDBFactory.cpp index 9c599e01e6..ac90243dd9 100644 --- a/src/ripple_core/nodestore/backend/HyperDBFactory.cpp +++ b/src/ripple_core/nodestore/backend/HyperDBFactory.cpp @@ -28,8 +28,6 @@ class HyperDBFactory::BackendImp , public LeakChecked { public: - typedef RecycledObjectPool StringPool; - BackendImp (size_t keyBytes, Parameters const& keyValues, Scheduler& scheduler) @@ -96,44 +94,38 @@ public: hyperleveldb::ReadOptions const options; hyperleveldb::Slice const slice (static_cast (key), m_keyBytes); + std::string string; + + hyperleveldb::Status getStatus = m_db->Get (options, slice, &string); + + if (getStatus.ok ()) { - // These are reused std::string objects, - // required for leveldb's funky interface. - // - StringPool::ScopedItem item (m_stringPool); - std::string& string = item.getObject (); + DecodedBlob decoded (key, string.data (), string.size ()); - hyperleveldb::Status getStatus = m_db->Get (options, slice, &string); - - if (getStatus.ok ()) + if (decoded.wasOk ()) { - DecodedBlob decoded (key, string.data (), string.size ()); - - if (decoded.wasOk ()) - { - *pObject = decoded.createObject (); - } - else - { - // Decoding failed, probably corrupted! - // - status = dataCorrupt; - } + *pObject = decoded.createObject (); } else { - if (getStatus.IsCorruption ()) - { - status = dataCorrupt; - } - else if (getStatus.IsNotFound ()) - { - status = notFound; - } - else - { - status = unknown; - } + // Decoding failed, probably corrupted! + // + status = dataCorrupt; + } + } + else + { + if (getStatus.IsCorruption ()) + { + status = dataCorrupt; + } + else if (getStatus.IsNotFound ()) + { + status = notFound; + } + else + { + status = unknown; } } @@ -149,19 +141,17 @@ public: { hyperleveldb::WriteBatch wb; + EncodedBlob encoded; + + BOOST_FOREACH (NodeObject::ref object, batch) { - EncodedBlob::Pool::ScopedItem item (m_blobPool); + encoded.prepare (object); - BOOST_FOREACH (NodeObject::ref object, batch) - { - item.getObject ().prepare (object); - - wb.Put ( - hyperleveldb::Slice (reinterpret_cast ( - item.getObject ().getKey ()), m_keyBytes), - hyperleveldb::Slice (reinterpret_cast ( - item.getObject ().getData ()), item.getObject ().getSize ())); - } + wb.Put ( + hyperleveldb::Slice (reinterpret_cast ( + encoded.getKey ()), m_keyBytes), + hyperleveldb::Slice (reinterpret_cast ( + encoded.getData ()), encoded.getSize ())); } hyperleveldb::WriteOptions const options; @@ -180,8 +170,7 @@ public: if (it->key ().size () == m_keyBytes) { DecodedBlob decoded (it->key ().data (), - it->value ().data (), - it->value ().size ()); + it->value ().data (), it->value ().size ()); if (decoded.wasOk ()) { @@ -220,8 +209,6 @@ private: size_t const m_keyBytes; Scheduler& m_scheduler; BatchWriter m_batch; - StringPool m_stringPool; - EncodedBlob::Pool m_blobPool; std::string m_name; ScopedPointer m_db; }; diff --git a/src/ripple_core/nodestore/backend/KeyvaDBFactory.cpp b/src/ripple_core/nodestore/backend/KeyvaDBFactory.cpp deleted file mode 100644 index dd4854b980..0000000000 --- a/src/ripple_core/nodestore/backend/KeyvaDBFactory.cpp +++ /dev/null @@ -1,193 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -namespace NodeStore -{ - -class KeyvaDBFactory::BackendImp : public Backend -{ -private: - typedef RecycledObjectPool MemoryPool; - typedef RecycledObjectPool EncodedBlobPool; - -public: - BackendImp (size_t keyBytes, - Parameters const& keyValues, - Scheduler& scheduler) - : m_keyBytes (keyBytes) - , m_scheduler (scheduler) - , m_path (keyValues ["path"]) - , m_db (KeyvaDB::New ( - keyBytes, - 3, - File::getCurrentWorkingDirectory().getChildFile (m_path).withFileExtension ("key"), - File::getCurrentWorkingDirectory().getChildFile (m_path).withFileExtension ("val"))) - { - } - - ~BackendImp () - { - } - - std::string getName () - { - return m_path.toStdString (); - } - - //-------------------------------------------------------------------------- - - Status fetch (void const* key, NodeObject::Ptr* pObject) - { - pObject->reset (); - - Status status (ok); - - struct Callback : KeyvaDB::GetCallback - { - explicit Callback (MemoryBlock& block) - : m_block (block) - { - } - - void* getStorageForValue (int valueBytes) - { - m_size = valueBytes; - m_block.ensureSize (valueBytes); - - return m_block.getData (); - } - - void const* getData () const noexcept - { - return m_block.getData (); - } - - size_t getSize () const noexcept - { - return m_size; - } - - private: - MemoryBlock& m_block; - size_t m_size; - }; - - MemoryPool::ScopedItem item (m_memoryPool); - MemoryBlock& block (item.getObject ()); - - Callback cb (block); - - // VFALCO TODO Can't we get KeyvaDB to provide a proper status? - // - bool const found = m_db->get (key, &cb); - - if (found) - { - DecodedBlob decoded (key, cb.getData (), cb.getSize ()); - - if (decoded.wasOk ()) - { - *pObject = decoded.createObject (); - - status = ok; - } - else - { - status = dataCorrupt; - } - } - else - { - status = notFound; - } - - return status; - } - - void store (NodeObject::ref object) - { - EncodedBlobPool::ScopedItem item (m_blobPool); - EncodedBlob& encoded (item.getObject ()); - - encoded.prepare (object); - - m_db->put (encoded.getKey (), encoded.getData (), encoded.getSize ()); - } - - void storeBatch (Batch const& batch) - { - for (std::size_t i = 0; i < batch.size (); ++i) - store (batch [i]); - } - - void visitAll (VisitCallback& callback) - { - // VFALCO TODO Implement this! - // - bassertfalse; - //m_db->visitAll (); - } - - int getWriteLoad () - { - // we dont do pending writes - return 0; - } - - //-------------------------------------------------------------------------- - -private: - size_t const m_keyBytes; - Scheduler& m_scheduler; - String m_path; - ScopedPointer m_db; - MemoryPool m_memoryPool; - EncodedBlobPool m_blobPool; -}; - -//------------------------------------------------------------------------------ - -KeyvaDBFactory::KeyvaDBFactory () -{ -} - -KeyvaDBFactory::~KeyvaDBFactory () -{ -} - -KeyvaDBFactory* KeyvaDBFactory::getInstance () -{ - return new KeyvaDBFactory; -} - -String KeyvaDBFactory::getName () const -{ - return "KeyvaDB"; -} - -Backend* KeyvaDBFactory::createInstance ( - size_t keyBytes, - Parameters const& keyValues, - Scheduler& scheduler, - Journal journal) -{ - return new KeyvaDBFactory::BackendImp (keyBytes, keyValues, scheduler); -} - -} diff --git a/src/ripple_core/nodestore/backend/KeyvaDBFactory.h b/src/ripple_core/nodestore/backend/KeyvaDBFactory.h deleted file mode 100644 index 60437b76b4..0000000000 --- a/src/ripple_core/nodestore/backend/KeyvaDBFactory.h +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef RIPPLE_NODESTORE_KEYVADBFACTORY_H_INCLUDED -#define RIPPLE_NODESTORE_KEYVADBFACTORY_H_INCLUDED - -namespace NodeStore -{ - -/** Factory to produce KeyvaDB backends for the NodeStore. - - @see Database -*/ -class KeyvaDBFactory : public Factory -{ -private: - KeyvaDBFactory (); - ~KeyvaDBFactory (); - -public: - class BackendImp; - - static KeyvaDBFactory* getInstance (); - - String getName () const; - - Backend* createInstance (size_t keyBytes, - Parameters const& keyValues, - Scheduler& scheduler, - Journal journal); -}; - -} - -#endif diff --git a/src/ripple_core/nodestore/backend/LevelDBFactory.cpp b/src/ripple_core/nodestore/backend/LevelDBFactory.cpp index f8f4c8e88b..1404dbc2cf 100644 --- a/src/ripple_core/nodestore/backend/LevelDBFactory.cpp +++ b/src/ripple_core/nodestore/backend/LevelDBFactory.cpp @@ -26,10 +26,6 @@ class LevelDBFactory::BackendImp , public LeakChecked { public: - typedef RecycledObjectPool StringPool; - - //-------------------------------------------------------------------------- - BackendImp (int keyBytes, Parameters const& keyValues, Scheduler& scheduler) @@ -95,45 +91,38 @@ public: leveldb::ReadOptions const options; leveldb::Slice const slice (static_cast (key), m_keyBytes); + std::string string; + leveldb::Status getStatus = m_db->Get (options, slice, &string); + + if (getStatus.ok ()) { - // These are reused std::string objects, - // required for leveldb's funky interface. - // - StringPool::ScopedItem item (m_stringPool); - std::string& string = item.getObject (); + DecodedBlob decoded (key, string.data (), string.size ()); - leveldb::Status getStatus = m_db->Get (options, slice, &string); - - if (getStatus.ok ()) + if (decoded.wasOk ()) { - DecodedBlob decoded (key, string.data (), string.size ()); - - if (decoded.wasOk ()) - { - *pObject = decoded.createObject (); - } - else - { - // Decoding failed, probably corrupted! - // - status = dataCorrupt; - } + *pObject = decoded.createObject (); } else { - if (getStatus.IsCorruption ()) - { - status = dataCorrupt; - } - else if (getStatus.IsNotFound ()) - { - status = notFound; - } - else - { - status = unknown; - } + // Decoding failed, probably corrupted! + // + status = dataCorrupt; + } + } + else + { + if (getStatus.IsCorruption ()) + { + status = dataCorrupt; + } + else if (getStatus.IsNotFound ()) + { + status = notFound; + } + else + { + status = unknown; } } @@ -149,19 +138,17 @@ public: { leveldb::WriteBatch wb; + EncodedBlob encoded; + + BOOST_FOREACH (NodeObject::ref object, batch) { - EncodedBlob::Pool::ScopedItem item (m_blobPool); + encoded.prepare (object); - BOOST_FOREACH (NodeObject::ref object, batch) - { - item.getObject ().prepare (object); - - wb.Put ( - leveldb::Slice (reinterpret_cast (item.getObject ().getKey ()), - m_keyBytes), - leveldb::Slice (reinterpret_cast (item.getObject ().getData ()), - item.getObject ().getSize ())); - } + wb.Put ( + leveldb::Slice (reinterpret_cast ( + encoded.getKey ()), m_keyBytes), + leveldb::Slice (reinterpret_cast ( + encoded.getData ()), encoded.getSize ())); } leveldb::WriteOptions const options; @@ -221,7 +208,6 @@ private: Scheduler& m_scheduler; BatchWriter m_batch; StringPool m_stringPool; - EncodedBlob::Pool m_blobPool; std::string m_name; ScopedPointer m_db; }; diff --git a/src/ripple_core/nodestore/backend/RocksDBFactory.cpp b/src/ripple_core/nodestore/backend/RocksDBFactory.cpp index 9bfc7a2e67..4fceddcf3e 100644 --- a/src/ripple_core/nodestore/backend/RocksDBFactory.cpp +++ b/src/ripple_core/nodestore/backend/RocksDBFactory.cpp @@ -80,10 +80,6 @@ class RocksDBFactory::BackendImp , public LeakChecked { public: - typedef RecycledObjectPool StringPool; - - //-------------------------------------------------------------------------- - BackendImp (int keyBytes, Parameters const& keyValues, Scheduler& scheduler, @@ -166,46 +162,40 @@ public: rocksdb::ReadOptions const options; rocksdb::Slice const slice (static_cast (key), m_keyBytes); + std::string string; + + rocksdb::Status getStatus = m_db->Get (options, slice, &string); + + if (getStatus.ok ()) { - // These are reused std::string objects, - // required for RocksDB's funky interface. - // - StringPool::ScopedItem item (m_stringPool); - std::string& string = item.getObject (); + DecodedBlob decoded (key, string.data (), string.size ()); - rocksdb::Status getStatus = m_db->Get (options, slice, &string); - - if (getStatus.ok ()) + if (decoded.wasOk ()) { - DecodedBlob decoded (key, string.data (), string.size ()); - - if (decoded.wasOk ()) - { - *pObject = decoded.createObject (); - } - else - { - // Decoding failed, probably corrupted! - // - status = dataCorrupt; - } + *pObject = decoded.createObject (); } else { - if (getStatus.IsCorruption ()) - { - status = dataCorrupt; - } - else if (getStatus.IsNotFound ()) - { - status = notFound; - } - else - { - status = Status (customCode + getStatus.code()); + // Decoding failed, probably corrupted! + // + status = dataCorrupt; + } + } + else + { + if (getStatus.IsCorruption ()) + { + status = dataCorrupt; + } + else if (getStatus.IsNotFound ()) + { + status = notFound; + } + else + { + status = Status (customCode + getStatus.code()); - m_journal.error << getStatus.ToString (); - } + m_journal.error << getStatus.ToString (); } } @@ -221,19 +211,17 @@ public: { rocksdb::WriteBatch wb; + EncodedBlob encoded; + + BOOST_FOREACH (NodeObject::ref object, batch) { - EncodedBlob::Pool::ScopedItem item (m_blobPool); + encoded.prepare (object); - BOOST_FOREACH (NodeObject::ref object, batch) - { - item.getObject ().prepare (object); - - wb.Put ( - rocksdb::Slice (reinterpret_cast (item.getObject ().getKey ()), - m_keyBytes), - rocksdb::Slice (reinterpret_cast (item.getObject ().getData ()), - item.getObject ().getSize ())); - } + wb.Put ( + rocksdb::Slice (reinterpret_cast ( + encoded.getKey ()), m_keyBytes), + rocksdb::Slice (reinterpret_cast ( + encoded.getData ()), encoded.getSize ())); } rocksdb::WriteOptions const options; @@ -293,8 +281,6 @@ private: size_t const m_keyBytes; Scheduler& m_scheduler; BatchWriter m_batch; - StringPool m_stringPool; - EncodedBlob::Pool m_blobPool; std::string m_name; ScopedPointer m_db; }; diff --git a/src/ripple_core/nodestore/backend/SophiaFactory.cpp b/src/ripple_core/nodestore/backend/SophiaFactory.cpp deleted file mode 100644 index 5f5405434c..0000000000 --- a/src/ripple_core/nodestore/backend/SophiaFactory.cpp +++ /dev/null @@ -1,204 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#if RIPPLE_SOPHIA_AVAILABLE - -namespace NodeStore -{ - -class SophiaFactory::BackendImp - : public Backend - , public BatchWriter::Callback - , public LeakChecked -{ -public: - typedef RecycledObjectPool StringPool; - - //-------------------------------------------------------------------------- - - BackendImp (int keyBytes, - Parameters const& keyValues, - Scheduler& scheduler) - : m_keyBytes (keyBytes) - , m_scheduler (scheduler) - , m_batch (*this, scheduler) - , m_name (keyValues ["path"].toStdString ()) - , m_env (nullptr) - , m_db (nullptr) - { - if (m_name.empty()) - Throw (std::runtime_error ("Missing path in Sophia backend")); - - m_env = sp_env (); - - if (m_env != nullptr) - { - sp_ctl (m_env, SPDIR, SPO_RDWR | SPO_CREAT, m_name.c_str()); - m_db = sp_open (m_env); - } - } - - ~BackendImp () - { - if (m_db != nullptr) - sp_destroy (m_db); - - if (m_env != nullptr) - sp_destroy (m_env); - } - - std::string getName() - { - return m_name; - } - - //-------------------------------------------------------------------------- - - Status fetch (void const* key, NodeObject::Ptr* pObject) - { - pObject->reset (); - - Status status (unknown); - - void* v (nullptr); - std::size_t vsize; - - int rc (sp_get (m_db, key, m_keyBytes, &v, &vsize)); - - if (rc == 1) - { - DecodedBlob decoded (key, v, vsize); - - if (decoded.wasOk ()) - { - *pObject = decoded.createObject (); - status = ok; - } - else - { - status = dataCorrupt; - } - - ::free (v); - } - else if (rc == 0) - { - status = notFound; - } - else - { - String s; - s << "Sophia failed with error code " << rc; - Throw (std::runtime_error (s.toStdString()), __FILE__, __LINE__); - status = notFound; - } - - return status; - } - - void store (NodeObject::ref object) - { - m_batch.store (object);; - } - - void storeBatch (Batch const& batch) - { - EncodedBlob::Pool::ScopedItem item (m_blobPool); - - for (Batch::const_iterator iter (batch.begin()); - iter != batch.end(); ++iter) - { - EncodedBlob& encoded (item.getObject ()); - encoded.prepare (*iter); - - int rv (sp_set (m_db, - encoded.getKey(), m_keyBytes, - encoded.getData(), encoded.getSize())); - - if (rv != 0) - { - String s; - s << "Sophia failed with error code " << rv; - Throw (std::runtime_error (s.toStdString()), __FILE__, __LINE__); - } - } - } - - void visitAll (VisitCallback& callback) - { - } - - int getWriteLoad () - { - return m_batch.getWriteLoad (); - } - - //-------------------------------------------------------------------------- - - void writeBatch (Batch const& batch) - { - storeBatch (batch); - } - -private: - size_t const m_keyBytes; - Scheduler& m_scheduler; - BatchWriter m_batch; - StringPool m_stringPool; - EncodedBlob::Pool m_blobPool; - std::string m_name; - void* m_env; - void* m_db; -}; - -//------------------------------------------------------------------------------ - -SophiaFactory::SophiaFactory () -{ - leveldb::Options options; - options.create_if_missing = true; - options.block_cache = leveldb::NewLRUCache (getConfig ().getSize ( - siHashNodeDBCache) * 1024 * 1024); -} - -SophiaFactory::~SophiaFactory () -{ -} - -SophiaFactory* SophiaFactory::getInstance () -{ - return new SophiaFactory; -} - -String SophiaFactory::getName () const -{ - return "sophia"; -} - -Backend* SophiaFactory::createInstance ( - size_t keyBytes, - Parameters const& keyValues, - Scheduler& scheduler) -{ - return new SophiaFactory::BackendImp (keyBytes, keyValues, scheduler); -} - -} - -#endif diff --git a/src/ripple_core/nodestore/backend/SophiaFactory.h b/src/ripple_core/nodestore/backend/SophiaFactory.h deleted file mode 100644 index 829493d65f..0000000000 --- a/src/ripple_core/nodestore/backend/SophiaFactory.h +++ /dev/null @@ -1,50 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef RIPPLE_NODESTORE_SOPHIAFACTORY_H_INCLUDED -#define RIPPLE_NODESTORE_SOPHIAFACTORY_H_INCLUDED - -namespace NodeStore -{ - -/** Factory to produce Sophia backends for the NodeStore. - - @see Database -*/ -class SophiaFactory : public Factory -{ -private: - SophiaFactory (); - ~SophiaFactory (); - -public: - class BackendImp; - - static SophiaFactory* getInstance (); - - String getName () const; - - NodeStore::Backend* createInstance (size_t keyBytes, - Parameters const& keyValues, - Scheduler& scheduler); -}; - -} - -#endif diff --git a/src/ripple_core/nodestore/impl/DatabaseImp.h b/src/ripple_core/nodestore/impl/DatabaseImp.h index d097ca1ee0..4ca6df9141 100644 --- a/src/ripple_core/nodestore/impl/DatabaseImp.h +++ b/src/ripple_core/nodestore/impl/DatabaseImp.h @@ -331,8 +331,6 @@ void Database::addAvailableBackends () #if RIPPLE_ROCKSDB_AVAILABLE addFactory (RocksDBFactory::New ()); #endif - - addFactory (KeyvaDBFactory::getInstance ()); } //------------------------------------------------------------------------------ diff --git a/src/ripple_core/nodestore/impl/EncodedBlob.h b/src/ripple_core/nodestore/impl/EncodedBlob.h index 04257979f1..801dd170bb 100644 --- a/src/ripple_core/nodestore/impl/EncodedBlob.h +++ b/src/ripple_core/nodestore/impl/EncodedBlob.h @@ -32,8 +32,6 @@ namespace NodeStore struct EncodedBlob { public: - typedef RecycledObjectPool Pool; - void prepare (NodeObject::Ptr const& object); void const* getKey () const noexcept { return m_key; } diff --git a/src/ripple_data/protocol/STAmount.cpp b/src/ripple_data/protocol/STAmount.cpp index d935a357e6..c75f5d3e56 100644 --- a/src/ripple_data/protocol/STAmount.cpp +++ b/src/ripple_data/protocol/STAmount.cpp @@ -1214,7 +1214,7 @@ STAmount STAmount::getPay (const STAmount& offerOut, const STAmount& offerIn, co STAmount STAmount::deserialize (SerializerIterator& it) { - UPTR_T s (dynamic_cast (construct (it, sfGeneric))); + std::unique_ptr s (dynamic_cast (construct (it, sfGeneric))); STAmount ret (*s); return ret; } diff --git a/src/ripple_data/protocol/SerializedObject.cpp b/src/ripple_data/protocol/SerializedObject.cpp index 11d50fcfe3..cc3504b6fe 100644 --- a/src/ripple_data/protocol/SerializedObject.cpp +++ b/src/ripple_data/protocol/SerializedObject.cpp @@ -19,56 +19,56 @@ SETUP_LOG (STObject) -UPTR_T STObject::makeDefaultObject (SerializedTypeID id, SField::ref name) +std::unique_ptr STObject::makeDefaultObject (SerializedTypeID id, SField::ref name) { assert ((id == STI_NOTPRESENT) || (id == name.fieldType)); switch (id) { case STI_NOTPRESENT: - return UPTR_T (new SerializedType (name)); + return std::unique_ptr (new SerializedType (name)); case STI_UINT8: - return UPTR_T (new STUInt8 (name)); + return std::unique_ptr (new STUInt8 (name)); case STI_UINT16: - return UPTR_T (new STUInt16 (name)); + return std::unique_ptr (new STUInt16 (name)); case STI_UINT32: - return UPTR_T (new STUInt32 (name)); + return std::unique_ptr (new STUInt32 (name)); case STI_UINT64: - return UPTR_T (new STUInt64 (name)); + return std::unique_ptr (new STUInt64 (name)); case STI_AMOUNT: - return UPTR_T (new STAmount (name)); + return std::unique_ptr (new STAmount (name)); case STI_HASH128: - return UPTR_T (new STHash128 (name)); + return std::unique_ptr (new STHash128 (name)); case STI_HASH160: - return UPTR_T (new STHash160 (name)); + return std::unique_ptr (new STHash160 (name)); case STI_HASH256: - return UPTR_T (new STHash256 (name)); + return std::unique_ptr (new STHash256 (name)); case STI_VECTOR256: - return UPTR_T (new STVector256 (name)); + return std::unique_ptr (new STVector256 (name)); case STI_VL: - return UPTR_T (new STVariableLength (name)); + return std::unique_ptr (new STVariableLength (name)); case STI_ACCOUNT: - return UPTR_T (new STAccount (name)); + return std::unique_ptr (new STAccount (name)); case STI_PATHSET: - return UPTR_T (new STPathSet (name)); + return std::unique_ptr (new STPathSet (name)); case STI_OBJECT: - return UPTR_T (new STObject (name)); + return std::unique_ptr (new STObject (name)); case STI_ARRAY: - return UPTR_T (new STArray (name)); + return std::unique_ptr (new STArray (name)); default: WriteLog (lsFATAL, STObject) << "Object type: " << lexicalCast (id); @@ -78,7 +78,7 @@ UPTR_T STObject::makeDefaultObject (SerializedTypeID id, SField: } // VFALCO TODO Remove the 'depth' parameter -UPTR_T STObject::makeDeserializedObject (SerializedTypeID id, SField::ref name, +std::unique_ptr STObject::makeDeserializedObject (SerializedTypeID id, SField::ref name, SerializerIterator& sit, int depth) { switch (id) @@ -297,10 +297,10 @@ bool STObject::set (SerializerIterator& sit, int depth) } -UPTR_T STObject::deserialize (SerializerIterator& sit, SField::ref name) +std::unique_ptr STObject::deserialize (SerializerIterator& sit, SField::ref name) { STObject* o; - UPTR_T object (o = new STObject (name)); + std::unique_ptr object (o = new STObject (name)); o->set (sit, 1); return object; } @@ -1232,7 +1232,7 @@ void STArray::sort (bool (*compare) (const STObject&, const STObject&)) value.sort (compare); } -UPTR_T STObject::parseJson (const Json::Value& object, SField::ref inName, int depth) +std::unique_ptr STObject::parseJson (const Json::Value& object, SField::ref inName, int depth) { if (!object.isObject ()) throw std::runtime_error ("Value is not an object"); @@ -1604,7 +1604,7 @@ UPTR_T STObject::parseJson (const Json::Value& object, SField::ref inN } } - return UPTR_T (new STObject (*name, data)); + return std::unique_ptr (new STObject (*name, data)); } //------------------------------------------------------------------------------ @@ -1652,7 +1652,7 @@ public: "\"DeletedNode\":{\"Sequence\":1}" "}]}"); - UPTR_T so; + std::unique_ptr so; Json::Value faultyJson; bool parsedOK (parseJSONString(faulty, faultyJson)); unexpected(!parsedOK, "failed to parse"); @@ -1677,7 +1677,7 @@ public: bool parsedOK (parseJSONString(json, jsonObject)); if (parsedOK) { - UPTR_T so; + std::unique_ptr so; so = STObject::parseJson (jsonObject); Json::FastWriter writer; std::string const& serialized (writer.write(so->getJson(0))); diff --git a/src/ripple_data/protocol/SerializedObject.h b/src/ripple_data/protocol/SerializedObject.h index cff413c539..1548c78467 100644 --- a/src/ripple_data/protocol/SerializedObject.h +++ b/src/ripple_data/protocol/SerializedObject.h @@ -48,19 +48,19 @@ public: setType (type); } - UPTR_T oClone () const + std::unique_ptr oClone () const { - return UPTR_T (new STObject (*this)); + return std::unique_ptr (new STObject (*this)); } - static UPTR_T parseJson (const Json::Value & value, SField::ref name = sfGeneric, int depth = 0); + static std::unique_ptr parseJson (const Json::Value & value, SField::ref name = sfGeneric, int depth = 0); virtual ~STObject () { ; } - static UPTR_T deserialize (SerializerIterator & sit, SField::ref name); + static std::unique_ptr deserialize (SerializerIterator & sit, SField::ref name); bool setType (const SOTemplate & type); bool isValidForType (); @@ -108,7 +108,7 @@ public: mData.push_back (t.clone ().release ()); return mData.size () - 1; } - int giveObject (UPTR_T t) + int giveObject (std::unique_ptr t) { mData.push_back (t.release ()); return mData.size () - 1; @@ -223,21 +223,21 @@ public: bool delField (SField::ref field); void delField (int index); - static UPTR_T makeDefaultObject (SerializedTypeID id, SField::ref name); + static std::unique_ptr makeDefaultObject (SerializedTypeID id, SField::ref name); // VFALCO TODO remove the 'depth' parameter - static UPTR_T makeDeserializedObject ( + static std::unique_ptr makeDeserializedObject ( SerializedTypeID id, SField::ref name, SerializerIterator&, int depth); - static UPTR_T makeNonPresentObject (SField::ref name) + static std::unique_ptr makeNonPresentObject (SField::ref name) { return makeDefaultObject (STI_NOTPRESENT, name); } - static UPTR_T makeDefaultObject (SField::ref name) + static std::unique_ptr makeDefaultObject (SField::ref name) { return makeDefaultObject (name.fieldType, name); } @@ -373,9 +373,9 @@ public: ; } - static UPTR_T deserialize (SerializerIterator & sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator & sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } const vector& getValue () const diff --git a/src/ripple_data/protocol/SerializedTypes.cpp b/src/ripple_data/protocol/SerializedTypes.cpp index 105cb87abf..fe94f2a729 100644 --- a/src/ripple_data/protocol/SerializedTypes.cpp +++ b/src/ripple_data/protocol/SerializedTypes.cpp @@ -330,7 +330,7 @@ STVector256* STVector256::construct (SerializerIterator& u, SField::ref name) Blob data = u.getVL (); Blob ::iterator begin = data.begin (); - UPTR_T vec (new STVector256 (name)); + std::unique_ptr vec (new STVector256 (name)); int count = data.size () / (256 / 8); vec->mValue.reserve (count); diff --git a/src/ripple_data/protocol/SerializedTypes.h b/src/ripple_data/protocol/SerializedTypes.h index 48a25e0297..bee83323f6 100644 --- a/src/ripple_data/protocol/SerializedTypes.h +++ b/src/ripple_data/protocol/SerializedTypes.h @@ -83,9 +83,9 @@ public: virtual ~SerializedType () { } - static UPTR_T deserialize (SField::ref name) + static std::unique_ptr deserialize (SField::ref name) { - return UPTR_T (new SerializedType (name)); + return std::unique_ptr (new SerializedType (name)); } void setFName (SField::ref n) @@ -106,9 +106,9 @@ public: { return STI_NOTPRESENT; } - UPTR_T clone () const + std::unique_ptr clone () const { - return UPTR_T (duplicate ()); + return std::unique_ptr (duplicate ()); } virtual std::string getFullText () const; @@ -185,9 +185,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } SerializedTypeID getSType () const @@ -242,9 +242,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } SerializedTypeID getSType () const @@ -299,9 +299,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } SerializedTypeID getSType () const @@ -356,9 +356,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } SerializedTypeID getSType () const @@ -492,9 +492,9 @@ public: static STAmount createFromInt64 (SField::ref n, int64 v); - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } bool bSetJson (const Json::Value& jvSource); @@ -832,9 +832,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } SerializedTypeID getSType () const @@ -903,9 +903,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } SerializedTypeID getSType () const @@ -974,9 +974,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } SerializedTypeID getSType () const @@ -1039,9 +1039,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } virtual SerializedTypeID getSType () const @@ -1111,9 +1111,9 @@ public: { ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } SerializedTypeID getSType () const @@ -1346,9 +1346,9 @@ public: ; } - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } // std::string getText() const; @@ -1508,9 +1508,9 @@ public: } void add (Serializer& s) const; - static UPTR_T deserialize (SerializerIterator& sit, SField::ref name) + static std::unique_ptr deserialize (SerializerIterator& sit, SField::ref name) { - return UPTR_T (construct (sit, name)); + return std::unique_ptr (construct (sit, name)); } const std::vector& peekValue () const diff --git a/src/ripple_net/basics/HTTPClient.cpp b/src/ripple_net/basics/HTTPClient.cpp index 7e159b767b..deb57f8b10 100644 --- a/src/ripple_net/basics/HTTPClient.cpp +++ b/src/ripple_net/basics/HTTPClient.cpp @@ -116,9 +116,9 @@ public: void request ( bool bSSL, std::deque deqSites, - FUNCTION_TYPE build, + std::function build, boost::posix_time::time_duration timeout, - FUNCTION_TYPE complete) { mSSL = bSSL; @@ -137,7 +137,7 @@ public: std::deque deqSites, const std::string& strPath, boost::posix_time::time_duration timeout, - FUNCTION_TYPE complete) { @@ -503,8 +503,8 @@ private: const unsigned short mPort; int mResponseMax; int mStatus; - FUNCTION_TYPE mBuild; - FUNCTION_TYPE mComplete; + std::function mBuild; + std::function mComplete; boost::asio::deadline_timer mDeadline; @@ -525,7 +525,7 @@ void HTTPClient::get ( const std::string& strPath, std::size_t responseMax, boost::posix_time::time_duration timeout, - FUNCTION_TYPE complete) { boost::shared_ptr client ( @@ -542,7 +542,7 @@ void HTTPClient::get ( const std::string& strPath, std::size_t responseMax, boost::posix_time::time_duration timeout, - FUNCTION_TYPE complete) { std::deque deqSites (1, strSite); @@ -558,10 +558,10 @@ void HTTPClient::request ( boost::asio::io_service& io_service, std::string strSite, const unsigned short port, - FUNCTION_TYPE setRequest, + std::function setRequest, std::size_t responseMax, boost::posix_time::time_duration timeout, - FUNCTION_TYPE complete) { std::deque deqSites (1, strSite); diff --git a/src/ripple_net/basics/HTTPClient.h b/src/ripple_net/basics/HTTPClient.h index 7a62538e2a..d9b6ccc1dd 100644 --- a/src/ripple_net/basics/HTTPClient.h +++ b/src/ripple_net/basics/HTTPClient.h @@ -40,7 +40,7 @@ public: const std::string& strPath, std::size_t responseMax, boost::posix_time::time_duration timeout, - FUNCTION_TYPE complete); + std::function complete); static void get ( bool bSSL, @@ -50,17 +50,17 @@ public: const std::string& strPath, std::size_t responseMax, boost::posix_time::time_duration timeout, - FUNCTION_TYPE complete); + std::function complete); static void request ( bool bSSL, boost::asio::io_service& io_service, std::string strSite, const unsigned short port, - FUNCTION_TYPE build, + std::function build, std::size_t responseMax, boost::posix_time::time_duration timeout, - FUNCTION_TYPE complete); + std::function complete); enum { diff --git a/src/ripple_net/rpc/RPCCall.cpp b/src/ripple_net/rpc/RPCCall.cpp index 66214cf6e0..853af3a273 100644 --- a/src/ripple_net/rpc/RPCCall.cpp +++ b/src/ripple_net/rpc/RPCCall.cpp @@ -945,7 +945,7 @@ struct RPCCallImp } static bool onResponse ( - FUNCTION_TYPE callbackFuncP, + std::function callbackFuncP, const boost::system::error_code& ecResult, int iStatus, const std::string& strData) { @@ -1125,7 +1125,7 @@ void RPCCall::fromNetwork ( const std::string& strUsername, const std::string& strPassword, const std::string& strPath, const std::string& strMethod, const Json::Value& jvParams, const bool bSSL, - FUNCTION_TYPE callbackFuncP) + std::function callbackFuncP) { // Connect to localhost if (!getConfig ().QUIET) diff --git a/src/ripple_net/rpc/RPCCall.h b/src/ripple_net/rpc/RPCCall.h index 6d58e64142..979e55ca93 100644 --- a/src/ripple_net/rpc/RPCCall.h +++ b/src/ripple_net/rpc/RPCCall.h @@ -41,7 +41,7 @@ public: const std::string& strUsername, const std::string& strPassword, const std::string& strPath, const std::string& strMethod, const Json::Value& jvParams, const bool bSSL, - FUNCTION_TYPE callbackFuncP = FUNCTION_TYPE ()); + std::function callbackFuncP = std::function ()); }; #endif diff --git a/src/ripple_websocket/autosocket/AutoSocket.h b/src/ripple_websocket/autosocket/AutoSocket.h index ff60a11285..5c5e4956ef 100644 --- a/src/ripple_websocket/autosocket/AutoSocket.h +++ b/src/ripple_websocket/autosocket/AutoSocket.h @@ -34,7 +34,7 @@ public: typedef ssl_socket::lowest_layer_type lowest_layer_type; typedef ssl_socket::handshake_type handshake_type; typedef boost::system::error_code error_code; - typedef boost::function callback; + typedef std::function callback; public: AutoSocket (boost::asio::io_service& s, boost::asio::ssl::context& c)