From db8fb177b833ff26cd6ba235ba2f03effe75af8a Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Mon, 11 Apr 2016 05:32:30 -0400 Subject: [PATCH] Remove unused or obsolete classes and files --- .gitignore | 2 +- Doxyfile | 302 -- SConstruct | 139 - beast/Boost.h | 27 - beast/ByteOrder.h | 298 -- beast/Chrono.h | 31 - beast/Config.h | 60 - beast/Crypto.h | 26 - beast/HeapBlock.h | 360 --- beast/Insight.h | 37 - beast/Intrusive.h | 26 - beast/Memory.h | 81 - beast/SmartPtr.h | 28 - beast/Threads.h | 29 - beast/Version.h | 45 - beast/asio/Asio.unity.cpp | 1 - beast/asio/IPAddressConversion.h | 68 - beast/asio/README.md | 14 - beast/asio/impl/IPAddressConversion.cpp | 67 - beast/asio/streambuf.h | 2 +- beast/asio/waitable_executor.h | 315 -- beast/boost/Boost.unity.cpp | 32 - beast/boost/ErrorCode.h | 35 - beast/chrono/Chrono.unity.cpp | 29 - beast/chrono/RelativeTime.h | 190 -- beast/chrono/impl/RelativeTime.cpp | 291 -- beast/chrono/ratio_io.h | 622 ---- beast/{utility => }/ci_char_traits.h | 0 beast/{chrono => clock}/abstract_clock.h | 0 beast/{chrono => clock}/basic_seconds_clock.h | 2 +- beast/{chrono => clock}/chrono_util.h | 0 beast/{chrono => clock}/manual_clock.h | 2 +- .../tests/beast_abstract_clock_test.cpp} | 4 +- .../tests/beast_basic_seconds_clock_test.cpp} | 2 +- beast/config/CompilerConfig.h | 151 - beast/config/ConfigCheck.h | 69 - beast/config/PlatformConfig.h | 211 -- beast/config/SelectCompilerConfig.h | 48 - beast/config/SelectPlatformConfig.h | 48 - beast/config/StandardConfig.h | 77 - beast/config/Suffix.h | 25 - beast/config/compiler/VisualC.h | 25 - beast/config/platform/Android.h | 30 - beast/config/platform/Bsd.h | 20 - beast/config/platform/Linux.h | 21 - beast/config/platform/MacOS.h | 21 - beast/config/platform/Win32.h | 21 - beast/container/Container.unity.cpp | 24 - beast/container/aged_container.h | 35 - beast/container/aged_container_utility.h | 51 - beast/container/aged_map.h | 43 - beast/container/aged_multimap.h | 43 - beast/container/aged_multiset.h | 42 - beast/container/aged_set.h | 42 - beast/container/aged_unordered_map.h | 44 - beast/container/aged_unordered_multimap.h | 44 - beast/container/aged_unordered_multiset.h | 43 - beast/container/aged_unordered_set.h | 43 - beast/container/buffer_view.h | 520 ---- beast/container/cyclic_iterator.h | 513 ---- .../detail/aged_associative_container.h | 54 - .../detail/aged_container_iterator.h | 182 -- .../container/detail/aged_ordered_container.h | 1969 ------------- .../detail/aged_unordered_container.h | 2554 ----------------- .../tests/aged_associative_container.test.cpp | 2011 ------------- beast/crypto/Crypto.unity.cpp | 24 - ...{base64.test.cpp => beast_base64_test.cpp} | 0 beast/{utility => }/empty_base_optimization.h | 4 +- beast/hash/hash_append.h | 3 +- beast/{utility => hash}/meta.h | 4 +- beast/hash/tests/hash_append_test.cpp | 2 +- beast/hash/tests/hash_speed_test.cpp | 42 +- beast/hash/uhash.h | 1 + beast/http/headers.h | 2 +- beast/http/message.h | 2 +- beast/http/method.h | 1 + beast/insight/Base.h | 38 - beast/insight/BaseImpl.h | 43 - beast/insight/Collector.h | 133 - beast/insight/Counter.h | 126 - beast/insight/CounterImpl.h | 44 - beast/insight/Event.h | 85 - beast/insight/EventImpl.h | 44 - beast/insight/Gauge.h | 143 - beast/insight/GaugeImpl.h | 46 - beast/insight/Group.h | 44 - beast/insight/Groups.h | 58 - beast/insight/Hook.h | 62 - beast/insight/HookImpl.h | 41 - beast/insight/Insight.unity.cpp | 34 - beast/insight/Meter.h | 97 - beast/insight/MeterImpl.h | 44 - beast/insight/NullCollector.h | 38 - beast/insight/StatsDCollector.h | 52 - beast/insight/impl/Collector.cpp | 28 - beast/insight/impl/Group.cpp | 28 - beast/insight/impl/Groups.cpp | 133 - beast/insight/impl/Hook.cpp | 28 - beast/insight/impl/Metric.cpp | 48 - beast/insight/impl/NullCollector.cpp | 137 - beast/insight/impl/StatsDCollector.cpp | 712 ----- beast/intrusive/List.h | 559 ---- beast/intrusive/LockFreeStack.h | 294 -- beast/module/README.md | 0 beast/module/asio/AsyncObject.h | 98 - beast/module/core/core.h | 78 - beast/module/core/core.unity.cpp | 188 -- beast/module/core/core.unity.mm | 30 - beast/module/core/diagnostic/FatalError.cpp | 65 - beast/module/core/diagnostic/FatalError.h | 45 - .../core/diagnostic/MeasureFunctionCallTime.h | 42 - .../core/diagnostic/SemanticVersion.cpp | 562 ---- .../module/core/diagnostic/SemanticVersion.h | 113 - .../core/diagnostic/UnitTestUtilities.cpp | 24 - beast/module/core/logging/Logger.h | 34 - beast/module/core/native/BasicNativeHeaders.h | 230 -- beast/module/core/native/bsd_SystemStats.cpp | 40 - .../module/core/native/linux_SystemStats.cpp | 42 - beast/module/core/native/mac_SystemStats.mm | 76 - beast/module/core/native/osx_ObjCHelpers.h | 54 - .../module/core/native/win32_SystemStats.cpp | 42 - beast/module/core/system/StandardIncludes.h | 78 - beast/module/core/system/SystemStats.cpp | 115 - beast/module/core/system/SystemStats.h | 44 - beast/module/core/text/LexicalCast.cpp | 281 -- beast/module/core/text/LexicalCast.h | 287 -- beast/module/core/thread/DeadlineTimer.cpp | 257 -- beast/module/core/thread/DeadlineTimer.h | 118 - beast/module/core/thread/MutexTraits.h | 24 - beast/module/core/thread/Workers.cpp | 293 -- beast/module/core/thread/Workers.h | 154 - beast/module/core/threads/ScopedLock.h | 258 -- beast/module/core/time/Time.cpp | 46 - beast/module/core/time/Time.h | 35 - beast/net/IPAddress.h | 358 --- beast/net/IPAddressV4.h | 201 -- beast/net/IPAddressV6.h | 108 - beast/net/IPEndpoint.h | 175 -- beast/net/Net.unity.cpp | 26 - beast/net/detail/Parse.h | 103 - beast/net/impl/IPAddressV4.cpp | 184 -- beast/net/impl/IPAddressV6.cpp | 83 - beast/net/impl/IPEndpoint.cpp | 174 -- beast/net/tests/IPEndpoint.test.cpp | 354 --- beast/nudb.h | 32 - beast/nudb/README.md | 288 -- beast/nudb/api.h | 110 - beast/nudb/common.h | 123 - beast/nudb/create.h | 164 -- beast/nudb/detail/arena.h | 246 -- beast/nudb/detail/bucket.h | 468 --- beast/nudb/detail/buffer.h | 99 - beast/nudb/detail/bulkio.h | 195 -- beast/nudb/detail/cache.h | 247 -- beast/nudb/detail/field.h | 275 -- beast/nudb/detail/format.h | 582 ---- beast/nudb/detail/gentex.h | 274 -- beast/nudb/detail/pool.h | 255 -- beast/nudb/detail/stream.h | 162 -- beast/nudb/detail/varint.h | 155 - beast/nudb/file.h | 40 - beast/nudb/identity.h | 64 - beast/nudb/nudb.cpp | 24 - beast/nudb/posix_file.h | 376 --- beast/nudb/recover.h | 157 - beast/nudb/store.h | 942 ------ beast/nudb/tests/callgrind_test.cpp | 111 - beast/nudb/tests/common.h | 259 -- beast/nudb/tests/fail_file.h | 245 -- beast/nudb/tests/recover_test.cpp | 180 -- beast/nudb/tests/store_test.cpp | 144 - beast/nudb/tests/varint_test.cpp | 73 - beast/nudb/tests/verify_test.cpp | 286 -- beast/nudb/verify.h | 532 ---- beast/nudb/visit.h | 111 - beast/nudb/win32_file.h | 462 --- beast/rngfill.h | 69 - beast/smart_ptr/SharedObject.h | 134 - beast/smart_ptr/SharedPtr.h | 327 --- beast/streams/streams.unity.cpp | 20 - ... => beast_basic_abstract_ostream_test.cpp} | 0 .../beast_empty_base_optimization_test.cpp} | 2 +- beast/threads/Stoppable.h | 378 --- beast/threads/Thread.h | 187 -- beast/threads/Threads.unity.cpp | 27 - beast/threads/WaitableEvent.h | 124 - beast/threads/impl/Stoppable.cpp | 215 -- beast/threads/impl/Stoppable.test.cpp | 451 --- beast/threads/impl/Thread.cpp | 293 -- beast/threads/impl/WaitableEvent.cpp | 168 -- beast/threads/semaphore.h | 86 - beast/{utility => }/type_name.h | 4 +- .../const_container.h | 4 +- beast/unit_test/results.h | 2 +- beast/unit_test/suite_list.h | 5 +- .../temp_dir.h} | 68 +- .../Clang.h => unity/beast_clock_unity.cpp} | 3 +- .../beast_crypto_unity.cpp} | 2 +- .../{hash_unity.cpp => beast_hash_unity.cpp} | 0 .../Gcc.h => unity/beast_streams_unity.cpp} | 2 +- .../Intel.h => unity/beast_test_unity.cpp} | 2 +- beast/utility/Debug.h | 66 - beast/utility/Journal.h | 360 --- beast/utility/PropertyStream.h | 360 --- beast/utility/Utility.unity.cpp | 32 - beast/utility/WrappedSink.h | 96 - beast/utility/Zero.h | 163 -- beast/utility/hash_pair.h | 70 - beast/utility/impl/Debug.cpp | 160 -- beast/utility/impl/Journal.cpp | 155 - beast/utility/impl/PropertyStream.cpp | 776 ----- beast/utility/make_lock.h | 38 - beast/utility/maybe_const.h | 42 - beast/utility/tagged_integer.h | 243 -- beast/utility/tests/Journal.test.cpp | 103 - beast/utility/tests/Zero.test.cpp | 142 - beast/utility/tests/tagged_integer.test.cpp | 154 - beast/utility/tests/weak_fn.test.cpp | 147 - beast/weak_fn.h | 175 -- beast/win32_workaround.h | 45 - beast/xor_shift_engine.h | 5 +- tests.sh | 11 - 222 files changed, 108 insertions(+), 34423 deletions(-) delete mode 100644 Doxyfile delete mode 100644 SConstruct delete mode 100644 beast/Boost.h delete mode 100644 beast/ByteOrder.h delete mode 100644 beast/Chrono.h delete mode 100644 beast/Config.h delete mode 100644 beast/Crypto.h delete mode 100644 beast/HeapBlock.h delete mode 100644 beast/Insight.h delete mode 100644 beast/Intrusive.h delete mode 100644 beast/Memory.h delete mode 100644 beast/SmartPtr.h delete mode 100644 beast/Threads.h delete mode 100644 beast/Version.h delete mode 100644 beast/asio/IPAddressConversion.h delete mode 100644 beast/asio/README.md delete mode 100644 beast/asio/impl/IPAddressConversion.cpp delete mode 100644 beast/asio/waitable_executor.h delete mode 100644 beast/boost/Boost.unity.cpp delete mode 100644 beast/boost/ErrorCode.h delete mode 100644 beast/chrono/Chrono.unity.cpp delete mode 100644 beast/chrono/RelativeTime.h delete mode 100644 beast/chrono/impl/RelativeTime.cpp delete mode 100644 beast/chrono/ratio_io.h rename beast/{utility => }/ci_char_traits.h (100%) rename beast/{chrono => clock}/abstract_clock.h (100%) rename beast/{chrono => clock}/basic_seconds_clock.h (99%) rename beast/{chrono => clock}/chrono_util.h (100%) rename beast/{chrono => clock}/manual_clock.h (98%) rename beast/{chrono/tests/abstract_clock.test.cpp => clock/tests/beast_abstract_clock_test.cpp} (97%) rename beast/{chrono/tests/basic_seconds_clock.test.cpp => clock/tests/beast_basic_seconds_clock_test.cpp} (96%) delete mode 100644 beast/config/CompilerConfig.h delete mode 100644 beast/config/ConfigCheck.h delete mode 100644 beast/config/PlatformConfig.h delete mode 100644 beast/config/SelectCompilerConfig.h delete mode 100644 beast/config/SelectPlatformConfig.h delete mode 100644 beast/config/StandardConfig.h delete mode 100644 beast/config/Suffix.h delete mode 100644 beast/config/compiler/VisualC.h delete mode 100644 beast/config/platform/Android.h delete mode 100644 beast/config/platform/Bsd.h delete mode 100644 beast/config/platform/Linux.h delete mode 100644 beast/config/platform/MacOS.h delete mode 100644 beast/config/platform/Win32.h delete mode 100644 beast/container/Container.unity.cpp delete mode 100644 beast/container/aged_container.h delete mode 100644 beast/container/aged_container_utility.h delete mode 100644 beast/container/aged_map.h delete mode 100644 beast/container/aged_multimap.h delete mode 100644 beast/container/aged_multiset.h delete mode 100644 beast/container/aged_set.h delete mode 100644 beast/container/aged_unordered_map.h delete mode 100644 beast/container/aged_unordered_multimap.h delete mode 100644 beast/container/aged_unordered_multiset.h delete mode 100644 beast/container/aged_unordered_set.h delete mode 100644 beast/container/buffer_view.h delete mode 100644 beast/container/cyclic_iterator.h delete mode 100644 beast/container/detail/aged_associative_container.h delete mode 100644 beast/container/detail/aged_container_iterator.h delete mode 100644 beast/container/detail/aged_ordered_container.h delete mode 100644 beast/container/detail/aged_unordered_container.h delete mode 100644 beast/container/tests/aged_associative_container.test.cpp delete mode 100644 beast/crypto/Crypto.unity.cpp rename beast/crypto/tests/{base64.test.cpp => beast_base64_test.cpp} (100%) rename beast/{utility => }/empty_base_optimization.h (95%) rename beast/{utility => hash}/meta.h (98%) delete mode 100644 beast/insight/Base.h delete mode 100644 beast/insight/BaseImpl.h delete mode 100644 beast/insight/Collector.h delete mode 100644 beast/insight/Counter.h delete mode 100644 beast/insight/CounterImpl.h delete mode 100644 beast/insight/Event.h delete mode 100644 beast/insight/EventImpl.h delete mode 100644 beast/insight/Gauge.h delete mode 100644 beast/insight/GaugeImpl.h delete mode 100644 beast/insight/Group.h delete mode 100644 beast/insight/Groups.h delete mode 100644 beast/insight/Hook.h delete mode 100644 beast/insight/HookImpl.h delete mode 100644 beast/insight/Insight.unity.cpp delete mode 100644 beast/insight/Meter.h delete mode 100644 beast/insight/MeterImpl.h delete mode 100644 beast/insight/NullCollector.h delete mode 100644 beast/insight/StatsDCollector.h delete mode 100644 beast/insight/impl/Collector.cpp delete mode 100644 beast/insight/impl/Group.cpp delete mode 100644 beast/insight/impl/Groups.cpp delete mode 100644 beast/insight/impl/Hook.cpp delete mode 100644 beast/insight/impl/Metric.cpp delete mode 100644 beast/insight/impl/NullCollector.cpp delete mode 100644 beast/insight/impl/StatsDCollector.cpp delete mode 100644 beast/intrusive/List.h delete mode 100644 beast/intrusive/LockFreeStack.h delete mode 100644 beast/module/README.md delete mode 100644 beast/module/asio/AsyncObject.h delete mode 100644 beast/module/core/core.h delete mode 100644 beast/module/core/core.unity.cpp delete mode 100644 beast/module/core/core.unity.mm delete mode 100644 beast/module/core/diagnostic/FatalError.cpp delete mode 100644 beast/module/core/diagnostic/FatalError.h delete mode 100644 beast/module/core/diagnostic/MeasureFunctionCallTime.h delete mode 100644 beast/module/core/diagnostic/SemanticVersion.cpp delete mode 100644 beast/module/core/diagnostic/SemanticVersion.h delete mode 100644 beast/module/core/diagnostic/UnitTestUtilities.cpp delete mode 100644 beast/module/core/logging/Logger.h delete mode 100644 beast/module/core/native/BasicNativeHeaders.h delete mode 100644 beast/module/core/native/bsd_SystemStats.cpp delete mode 100644 beast/module/core/native/linux_SystemStats.cpp delete mode 100644 beast/module/core/native/mac_SystemStats.mm delete mode 100644 beast/module/core/native/osx_ObjCHelpers.h delete mode 100644 beast/module/core/native/win32_SystemStats.cpp delete mode 100644 beast/module/core/system/StandardIncludes.h delete mode 100644 beast/module/core/system/SystemStats.cpp delete mode 100644 beast/module/core/system/SystemStats.h delete mode 100644 beast/module/core/text/LexicalCast.cpp delete mode 100644 beast/module/core/text/LexicalCast.h delete mode 100644 beast/module/core/thread/DeadlineTimer.cpp delete mode 100644 beast/module/core/thread/DeadlineTimer.h delete mode 100644 beast/module/core/thread/MutexTraits.h delete mode 100644 beast/module/core/thread/Workers.cpp delete mode 100644 beast/module/core/thread/Workers.h delete mode 100644 beast/module/core/threads/ScopedLock.h delete mode 100644 beast/module/core/time/Time.cpp delete mode 100644 beast/module/core/time/Time.h delete mode 100644 beast/net/IPAddress.h delete mode 100644 beast/net/IPAddressV4.h delete mode 100644 beast/net/IPAddressV6.h delete mode 100644 beast/net/IPEndpoint.h delete mode 100644 beast/net/Net.unity.cpp delete mode 100644 beast/net/detail/Parse.h delete mode 100644 beast/net/impl/IPAddressV4.cpp delete mode 100644 beast/net/impl/IPAddressV6.cpp delete mode 100644 beast/net/impl/IPEndpoint.cpp delete mode 100644 beast/net/tests/IPEndpoint.test.cpp delete mode 100644 beast/nudb.h delete mode 100644 beast/nudb/README.md delete mode 100644 beast/nudb/api.h delete mode 100644 beast/nudb/common.h delete mode 100644 beast/nudb/create.h delete mode 100644 beast/nudb/detail/arena.h delete mode 100644 beast/nudb/detail/bucket.h delete mode 100644 beast/nudb/detail/buffer.h delete mode 100644 beast/nudb/detail/bulkio.h delete mode 100644 beast/nudb/detail/cache.h delete mode 100644 beast/nudb/detail/field.h delete mode 100644 beast/nudb/detail/format.h delete mode 100644 beast/nudb/detail/gentex.h delete mode 100644 beast/nudb/detail/pool.h delete mode 100644 beast/nudb/detail/stream.h delete mode 100644 beast/nudb/detail/varint.h delete mode 100644 beast/nudb/file.h delete mode 100644 beast/nudb/identity.h delete mode 100644 beast/nudb/nudb.cpp delete mode 100644 beast/nudb/posix_file.h delete mode 100644 beast/nudb/recover.h delete mode 100644 beast/nudb/store.h delete mode 100644 beast/nudb/tests/callgrind_test.cpp delete mode 100644 beast/nudb/tests/common.h delete mode 100644 beast/nudb/tests/fail_file.h delete mode 100644 beast/nudb/tests/recover_test.cpp delete mode 100644 beast/nudb/tests/store_test.cpp delete mode 100644 beast/nudb/tests/varint_test.cpp delete mode 100644 beast/nudb/tests/verify_test.cpp delete mode 100644 beast/nudb/verify.h delete mode 100644 beast/nudb/visit.h delete mode 100644 beast/nudb/win32_file.h delete mode 100644 beast/rngfill.h delete mode 100644 beast/smart_ptr/SharedObject.h delete mode 100644 beast/smart_ptr/SharedPtr.h delete mode 100644 beast/streams/streams.unity.cpp rename beast/streams/tests/{basic_abstract_ostream.test.cpp => beast_basic_abstract_ostream_test.cpp} (100%) rename beast/{utility/tests/empty_base_optimization.test.cpp => test/beast_empty_base_optimization_test.cpp} (98%) delete mode 100644 beast/threads/Stoppable.h delete mode 100644 beast/threads/Thread.h delete mode 100644 beast/threads/Threads.unity.cpp delete mode 100644 beast/threads/WaitableEvent.h delete mode 100644 beast/threads/impl/Stoppable.cpp delete mode 100644 beast/threads/impl/Stoppable.test.cpp delete mode 100644 beast/threads/impl/Thread.cpp delete mode 100644 beast/threads/impl/WaitableEvent.cpp delete mode 100644 beast/threads/semaphore.h rename beast/{utility => }/type_name.h (96%) rename beast/{container => unit_test}/const_container.h (96%) rename beast/{module/core/diagnostic/UnitTestUtilities.h => unit_test/temp_dir.h} (54%) rename beast/{config/compiler/Clang.h => unity/beast_clock_unity.cpp} (89%) rename beast/{config/SelectStdlibConfig.h => unity/beast_crypto_unity.cpp} (95%) rename beast/unity/{hash_unity.cpp => beast_hash_unity.cpp} (100%) rename beast/{config/compiler/Gcc.h => unity/beast_streams_unity.cpp} (93%) rename beast/{config/compiler/Intel.h => unity/beast_test_unity.cpp} (94%) delete mode 100644 beast/utility/Debug.h delete mode 100644 beast/utility/Journal.h delete mode 100644 beast/utility/PropertyStream.h delete mode 100644 beast/utility/Utility.unity.cpp delete mode 100644 beast/utility/WrappedSink.h delete mode 100644 beast/utility/Zero.h delete mode 100644 beast/utility/hash_pair.h delete mode 100644 beast/utility/impl/Debug.cpp delete mode 100644 beast/utility/impl/Journal.cpp delete mode 100644 beast/utility/impl/PropertyStream.cpp delete mode 100644 beast/utility/make_lock.h delete mode 100644 beast/utility/maybe_const.h delete mode 100644 beast/utility/tagged_integer.h delete mode 100644 beast/utility/tests/Journal.test.cpp delete mode 100644 beast/utility/tests/Zero.test.cpp delete mode 100644 beast/utility/tests/tagged_integer.test.cpp delete mode 100644 beast/utility/tests/weak_fn.test.cpp delete mode 100644 beast/weak_fn.h delete mode 100644 beast/win32_workaround.h delete mode 100755 tests.sh diff --git a/.gitignore b/.gitignore index 0cda894e60..f2c52757cf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -Docs +docs/ ._* *.mode1v3 *.pbxuser diff --git a/Doxyfile b/Doxyfile deleted file mode 100644 index b6e7241066..0000000000 --- a/Doxyfile +++ /dev/null @@ -1,302 +0,0 @@ -# Doxyfile 1.8.3.1 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -DOXYFILE_ENCODING = UTF-8 -PROJECT_NAME = "Beast" -PROJECT_NUMBER = -PROJECT_BRIEF = -PROJECT_LOGO = -OUTPUT_DIRECTORY = Docs -CREATE_SUBDIRS = NO -OUTPUT_LANGUAGE = English -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -QT_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -INHERIT_DOCS = YES -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 4 -ALIASES = -TCL_SUBST = -OPTIMIZE_OUTPUT_FOR_C = NO -OPTIMIZE_OUTPUT_JAVA = NO -OPTIMIZE_FOR_FORTRAN = NO -OPTIMIZE_OUTPUT_VHDL = NO -EXTENSION_MAPPING = -MARKDOWN_SUPPORT = YES -AUTOLINK_SUPPORT = YES -BUILTIN_STL_SUPPORT = NO -CPP_CLI_SUPPORT = NO -SIP_SUPPORT = NO -IDL_PROPERTY_SUPPORT = YES -DISTRIBUTE_GROUP_DOC = NO -SUBGROUPING = YES -INLINE_GROUPED_CLASSES = NO -INLINE_SIMPLE_STRUCTS = NO -TYPEDEF_HIDES_STRUCT = NO -SYMBOL_CACHE_SIZE = 0 -LOOKUP_CACHE_SIZE = 0 -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = NO -EXTRACT_PRIVATE = NO -EXTRACT_PACKAGE = NO -EXTRACT_STATIC = NO -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -EXTRACT_ANON_NSPACES = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = NO -HIDE_SCOPE_NAMES = NO -SHOW_INCLUDE_FILES = YES -FORCE_LOCAL_INCLUDES = NO -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_MEMBERS_CTORS_1ST = NO -SORT_GROUP_NAMES = NO -SORT_BY_SCOPE_NAME = NO -STRICT_PROTO_MATCHING = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_FILES = YES -SHOW_NAMESPACES = YES -FILE_VERSION_FILTER = -LAYOUT_FILE = -CITE_BIB_FILES = -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = modules -INPUT_ENCODING = UTF-8 -FILE_PATTERNS = -RECURSIVE = YES -EXCLUDE = modules/beast_core/beast_core.h \ - modules/beast_core/beast_core.unity.cpp \ - modules/beast_basics/beast_basics.cpp \ - modules/beast_basics/native \ - modules/beast_basics/zip/zlib -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXCLUDE_SYMBOLS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = NO -FILTER_SOURCE_PATTERNS = -USE_MDFILE_AS_MAINPAGE = -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = NO -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -REFERENCES_LINK_SOURCE = YES -USE_HTAGS = NO -VERBATIM_HEADERS = YES -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = YES -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = . -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_EXTRA_STYLESHEET = -HTML_EXTRA_FILES = -HTML_COLORSTYLE_HUE = 220 -HTML_COLORSTYLE_SAT = 100 -HTML_COLORSTYLE_GAMMA = 80 -HTML_TIMESTAMP = YES -HTML_DYNAMIC_SECTIONS = NO -HTML_INDEX_NUM_ENTRIES = 100 -GENERATE_DOCSET = NO -DOCSET_FEEDNAME = "Doxygen generated docs" -DOCSET_BUNDLE_ID = org.doxygen.Project -DOCSET_PUBLISHER_ID = org.doxygen.Publisher -DOCSET_PUBLISHER_NAME = Publisher -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -CHM_INDEX_ENCODING = -BINARY_TOC = NO -TOC_EXPAND = NO -GENERATE_QHP = NO -QCH_FILE = -QHP_NAMESPACE = org.doxygen.Project -QHP_VIRTUAL_FOLDER = doc -QHP_CUST_FILTER_NAME = -QHP_CUST_FILTER_ATTRS = -QHP_SECT_FILTER_ATTRS = -QHG_LOCATION = -GENERATE_ECLIPSEHELP = NO -ECLIPSE_DOC_ID = org.doxygen.Project -DISABLE_INDEX = NO -GENERATE_TREEVIEW = NO -ENUM_VALUES_PER_LINE = 4 -TREEVIEW_WIDTH = 250 -EXT_LINKS_IN_WINDOW = NO -FORMULA_FONTSIZE = 10 -FORMULA_TRANSPARENT = YES -USE_MATHJAX = NO -MATHJAX_FORMAT = HTML-CSS -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest -MATHJAX_EXTENSIONS = -SEARCHENGINE = YES -SERVER_BASED_SEARCH = NO -EXTERNAL_SEARCH = NO -SEARCHENGINE_URL = -SEARCHDATA_FILE = searchdata.xml -EXTERNAL_SEARCH_ID = -EXTRA_SEARCH_MAPPINGS = -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4 -EXTRA_PACKAGES = -LATEX_HEADER = -LATEX_FOOTER = -PDF_HYPERLINKS = YES -USE_PDFLATEX = YES -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -LATEX_SOURCE_CODE = NO -LATEX_BIB_STYLE = plain -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_LINKS = NO -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -MSCGEN_PATH = -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = YES -DOT_NUM_THREADS = 0 -DOT_FONTNAME = Helvetica -DOT_FONTSIZE = 10 -DOT_FONTPATH = -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -UML_LIMIT_NUM_FIELDS = 10 -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -CALLER_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -INTERACTIVE_SVG = NO -DOT_PATH = -DOTFILE_DIRS = -MSCFILE_DIRS = -DOT_GRAPH_MAX_NODES = 50 -MAX_DOT_GRAPH_DEPTH = 0 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES - diff --git a/SConstruct b/SConstruct deleted file mode 100644 index 80b5919836..0000000000 --- a/SConstruct +++ /dev/null @@ -1,139 +0,0 @@ -from __future__ import absolute_import, division, print_function, unicode_literals - -import copy -import itertools -import ntpath -import os -import random -import sys - -def add_beast_to_path(): - python_home = os.path.join(os.getcwd(), 'python') - if python_home not in sys.path: - sys.path.append(python_home) - -add_beast_to_path() - -from beast.env.AddCommonFlags import add_common_flags -from beast.env.AddUserEnv import add_user_env -from beast.env import Print -from beast.platform import GetEnvironment -from beast.util import Boost -from beast.util import File -from beast.util import Tests - -VARIANT_DIRECTORIES = { - 'beast': ('bin', 'beast'), - 'modules': ('bin', 'modules'), -} - -BOOST_LIBRARIES = '' #boost_system' -MAIN_PROGRAM_FILE = 'beast/unit_test/tests/main.cpp' -DOTFILE = '~/.scons' - -def main(): - File.validate_libraries(Boost.LIBPATH, BOOST_LIBRARIES) - defaults = GetEnvironment.get_environment(ARGUMENTS) - working = copy.deepcopy(defaults) - add_common_flags(defaults) - - add_user_env(working, DOTFILE) - add_common_flags(working) - Print.print_build_config(working, defaults) - - env = Environment(**working) - - for name, path in VARIANT_DIRECTORIES.items(): - env.VariantDir(os.path.join(*path), name, duplicate=0) - env.Replace(PRINT_CMD_LINE_FUNC=Print.print_cmd_line) - #Tests.run_tests(env, MAIN_PROGRAM_FILE, '.', '.test.cpp') - -#main() - -#------------------------------------------------------------------------------- - -def is_unity(path): - b, e = os.path.splitext(path) - return os.path.splitext(b)[1] == '.unity' and e in ['.c', '.cpp'] - -def files(base): - for parent, _, files in os.walk(base): - for path in files: - path = os.path.join(parent, path) - yield os.path.normpath(path) - -#------------------------------------------------------------------------------- - -''' -/MP /GS /W3 /wd"4018" /wd"4244" /wd"4267" /Gy- /Zc:wchar_t -/I"D:\lib\OpenSSL-Win64\include" /I"D:\lib\boost_1_55_0" -/I"..\..\src\protobuf\src" /I"..\..\src\protobuf\vsprojects" -/I"..\..\src\leveldb" /I"..\..\src\leveldb\include" /I"..\..\build\proto" -/Zi /Gm- /Od /Fd"..\..\build\obj\VisualStudio2013\Debug.x64\vc120.pdb" -/fp:precise /D "_CRTDBG_MAP_ALLOC" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" -/D "_VARIADIC_MAX=10" /D "_WIN32_WINNT=0x0600" /D "_SCL_SECURE_NO_WARNINGS" -/D "_CRT_SECURE_NO_WARNINGS" /D "_MBCS" /errorReport:prompt /WX- /Zc:forScope -/RTC1 /GR /Gd /MTd /openmp- /Fa"..\..\build\obj\VisualStudio2013\Debug.x64\" -/EHa /nologo /Fo"..\..\build\obj\VisualStudio2013\Debug.x64\" -/Fp"..\..\build\obj\VisualStudio2013\Debug.x64\rippled.pch" -''' - -# Path to this SConstruct file -base_dir = Dir('#').srcnode().get_abspath() - -base_env = Environment( - tools = ['default', 'VSProject'], - CCCOMSTR = '', - CMDLINE_QUIET = 1, - CPPPATH = [ - os.environ['BOOST_ROOT'], - os.environ['OPENSSL_ROOT'] - ], - CPPDEFINES = [ - '_WIN32_WINNT=0x6000'] - ) - -#base_env.Replace(PRINT_CMD_LINE_FUNC=Print.print_cmd_line) - -env = base_env - -bin_dir = os.path.join(base_dir, 'bin') - -srcs = filter(is_unity, list(files('beast')) + list(files('modules'))) -for variant in ['Debug']: #, 'Release']: - for platform in ['Win32']: - #env = base_env.Clone() - #env.Replace(PRINT_CMD_LINE_FUNC=Print.print_cmd_line) - variant_dir = os.path.join(bin_dir, variant + '.' + platform) - env.VariantDir(os.path.join(variant_dir, 'beast'), 'beast', duplicate=0) - env.VariantDir(os.path.join(variant_dir, 'modules'), 'modules', duplicate=0) - env.Append(CCFLAGS=[ - '/EHsc', - '/bigobj', - '/Fd${TARGET}.pdb' - ]) - if variant == 'Debug': - env.Append(CCFLAGS=[ - '/MTd', - '/Od', - '/Zi' - ]) - else: - env.Append(CCFLAGS=[ - '/MT', - '/Ox' - ]) - variant_srcs = [os.path.join(variant_dir, os.path.relpath(f, base_dir)) for f in srcs] - - beast = env.StaticLibrary( - target = os.path.join(variant_dir, 'beast.lib'), - source = variant_srcs) - -env.VSProject ( - 'out', - buildtarget = beast, - source = filter(is_unity, list(files('beast')) + list(files('modules')))) - -env.Default ('out.vcxproj') -#env.Default (os.path.join(bin_dir,'Debug.Win32', 'beast.lib')) - diff --git a/beast/Boost.h b/beast/Boost.h deleted file mode 100644 index 4746c0a874..0000000000 --- a/beast/Boost.h +++ /dev/null @@ -1,27 +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_BOOST_H_INCLUDED -#define BEAST_BOOST_H_INCLUDED - -// These classes require boost in order to be used. - -#include - -#endif diff --git a/beast/ByteOrder.h b/beast/ByteOrder.h deleted file mode 100644 index 67c94cb6b0..0000000000 --- a/beast/ByteOrder.h +++ /dev/null @@ -1,298 +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_BYTEORDER_H_INCLUDED -#define BEAST_BYTEORDER_H_INCLUDED - -#include - -#include - -namespace beast { - -//============================================================================== -/** Contains static methods for converting the byte order between different - endiannesses. -*/ -class ByteOrder -{ -public: - //============================================================================== - /** Swaps the upper and lower bytes of a 16-bit integer. */ - static std::uint16_t swap (std::uint16_t value); - - /** Reverses the order of the 4 bytes in a 32-bit integer. */ - static std::uint32_t swap (std::uint32_t value); - - /** Reverses the order of the 8 bytes in a 64-bit integer. */ - static std::uint64_t swap (std::uint64_t value); - - //============================================================================== - /** Swaps the byte order of a 16-bit int if the CPU is big-endian */ - static std::uint16_t swapIfBigEndian (std::uint16_t value); - - /** Swaps the byte order of a 32-bit int if the CPU is big-endian */ - static std::uint32_t swapIfBigEndian (std::uint32_t value); - - /** Swaps the byte order of a 64-bit int if the CPU is big-endian */ - static std::uint64_t swapIfBigEndian (std::uint64_t value); - - /** Swaps the byte order of a 16-bit int if the CPU is little-endian */ - static std::uint16_t swapIfLittleEndian (std::uint16_t value); - - /** Swaps the byte order of a 32-bit int if the CPU is little-endian */ - static std::uint32_t swapIfLittleEndian (std::uint32_t value); - - /** Swaps the byte order of a 64-bit int if the CPU is little-endian */ - static std::uint64_t swapIfLittleEndian (std::uint64_t value); - - //============================================================================== - /** Turns 2 bytes into a little-endian integer. */ - static std::uint16_t littleEndianShort (const void* bytes); - - /** Turns 4 bytes into a little-endian integer. */ - static std::uint32_t littleEndianInt (const void* bytes); - - /** Turns 4 bytes into a little-endian integer. */ - static std::uint64_t littleEndianInt64 (const void* bytes); - - /** Turns 2 bytes into a big-endian integer. */ - static std::uint16_t bigEndianShort (const void* bytes); - - /** Turns 4 bytes into a big-endian integer. */ - static std::uint32_t bigEndianInt (const void* bytes); - - /** Turns 4 bytes into a big-endian integer. */ - static std::uint64_t bigEndianInt64 (const void* bytes); - - //============================================================================== - /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */ - static int littleEndian24Bit (const char* bytes); - - /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */ - static int bigEndian24Bit (const char* bytes); - - /** Copies a 24-bit number to 3 little-endian bytes. */ - static void littleEndian24BitToChars (int value, char* destBytes); - - /** Copies a 24-bit number to 3 big-endian bytes. */ - static void bigEndian24BitToChars (int value, char* destBytes); - - //============================================================================== - /** Returns true if the current CPU is big-endian. */ - static bool isBigEndian(); - -private: - ByteOrder(); - ByteOrder(ByteOrder const&) = delete; - ByteOrder& operator= (ByteOrder const&) = delete; -}; - -//============================================================================== -#if BEAST_USE_INTRINSICS && ! defined (__INTEL_COMPILER) - #pragma intrinsic (_byteswap_ulong) -#endif - -inline std::uint16_t ByteOrder::swap (std::uint16_t n) -{ - #if BEAST_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic! - return static_cast (_byteswap_ushort (n)); - #else - return static_cast ((n << 8) | (n >> 8)); - #endif -} - -inline std::uint32_t ByteOrder::swap (std::uint32_t n) -{ - #if BEAST_MAC || BEAST_IOS - return OSSwapInt32 (n); - #elif BEAST_GCC && BEAST_INTEL && ! BEAST_NO_INLINE_ASM - asm("bswap %%eax" : "=a"(n) : "a"(n)); - return n; - #elif BEAST_USE_INTRINSICS - return _byteswap_ulong (n); - #elif BEAST_MSVC && ! BEAST_NO_INLINE_ASM - __asm { - mov eax, n - bswap eax - mov n, eax - } - return n; - #elif BEAST_ANDROID - return bswap_32 (n); - #else - return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8); - #endif -} - -inline std::uint64_t ByteOrder::swap (std::uint64_t value) -{ - #if BEAST_MAC || BEAST_IOS - return OSSwapInt64 (value); - #elif BEAST_USE_INTRINSICS - return _byteswap_uint64 (value); - #else - return (((std::int64_t) swap ((std::uint32_t) value)) << 32) | swap ((std::uint32_t) (value >> 32)); - #endif -} - -#if BEAST_LITTLE_ENDIAN - inline std::uint16_t ByteOrder::swapIfBigEndian (const std::uint16_t v) { return v; } - inline std::uint32_t ByteOrder::swapIfBigEndian (const std::uint32_t v) { return v; } - inline std::uint64_t ByteOrder::swapIfBigEndian (const std::uint64_t v) { return v; } - inline std::uint16_t ByteOrder::swapIfLittleEndian (const std::uint16_t v) { return swap (v); } - inline std::uint32_t ByteOrder::swapIfLittleEndian (const std::uint32_t v) { return swap (v); } - inline std::uint64_t ByteOrder::swapIfLittleEndian (const std::uint64_t v) { return swap (v); } - inline std::uint16_t ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast (bytes); } - inline std::uint32_t ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast (bytes); } - inline std::uint64_t ByteOrder::littleEndianInt64 (const void* const bytes) { return *static_cast (bytes); } - inline std::uint16_t ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast (bytes)); } - inline std::uint32_t ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast (bytes)); } - inline std::uint64_t ByteOrder::bigEndianInt64 (const void* const bytes) { return swap (*static_cast (bytes)); } - inline bool ByteOrder::isBigEndian() { return false; } -#else - inline std::uint16_t ByteOrder::swapIfBigEndian (const std::uint16_t v) { return swap (v); } - inline std::uint32_t ByteOrder::swapIfBigEndian (const std::uint32_t v) { return swap (v); } - inline std::uint64_t ByteOrder::swapIfBigEndian (const std::uint64_t v) { return swap (v); } - inline std::uint16_t ByteOrder::swapIfLittleEndian (const std::uint16_t v) { return v; } - inline std::uint32_t ByteOrder::swapIfLittleEndian (const std::uint32_t v) { return v; } - inline std::uint64_t ByteOrder::swapIfLittleEndian (const std::uint64_t v) { return v; } - inline std::uint32_t ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast (bytes)); } - inline std::uint16_t ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast (bytes)); } - inline std::uint16_t ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast (bytes); } - inline std::uint32_t ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast (bytes); } - inline std::uint64_t ByteOrder::bigEndianInt64 (const void* const bytes) { return *static_cast (bytes); } - inline bool ByteOrder::isBigEndian() { return true; } -#endif - -inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((int) (std::uint8_t) bytes[1]) << 8) | ((int) (std::uint8_t) bytes[0]); } -inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((int) (std::uint8_t) bytes[1]) << 8) | ((int) (std::uint8_t) bytes[2]); } -inline void ByteOrder::littleEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); } -inline void ByteOrder::bigEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); } - -namespace detail -{ - -/** Specialized helper class template for swapping bytes. - - Normally you won't use this directly, use the helper function - byteSwap instead. You can specialize this class for your - own user defined types, as was done for uint24. - - @see swapBytes, uint24 -*/ -template -struct SwapBytes -{ - inline IntegralType operator() (IntegralType value) const noexcept - { - return ByteOrder::swap (value); - } -}; - -// Specializations for signed integers - -template <> -struct SwapBytes -{ - inline std::int16_t operator() (std::int16_t value) const noexcept - { - return static_cast (ByteOrder::swap (static_cast (value))); - } -}; - -template <> -struct SwapBytes -{ - inline std::int32_t operator() (std::int32_t value) const noexcept - { - return static_cast (ByteOrder::swap (static_cast (value))); - } -}; - -template <> -struct SwapBytes -{ - inline std::int64_t operator() (std::int64_t value) const noexcept - { - return static_cast (ByteOrder::swap (static_cast (value))); - } -}; - -} - -//------------------------------------------------------------------------------ - -/** Returns a type with the bytes swapped. - Little endian becomes big endian and vice versa. The underlying - type must be an integral type or behave like one. -*/ -template -inline IntegralType swapBytes (IntegralType value) noexcept -{ - return detail::SwapBytes () (value); -} - -/** Returns the machine byte-order value to little-endian byte order. */ -template -inline IntegralType toLittleEndian (IntegralType value) noexcept -{ -#if BEAST_LITTLE_ENDIAN - return value; -#else - return swapBytes (value); -#endif -} - -/** Returns the machine byte-order value to big-endian byte order. */ -template -inline IntegralType toBigEndian (IntegralType value) noexcept -{ -#if BEAST_LITTLE_ENDIAN - return swapBytes (value); -#else - return value; -#endif -} - -/** Returns the machine byte-order value to network byte order. */ -template -inline IntegralType toNetworkByteOrder (IntegralType value) noexcept -{ - return toBigEndian (value); -} - -/** Converts from network byte order to machine byte order. */ -template -inline IntegralType fromNetworkByteOrder (IntegralType value) noexcept -{ -#if BEAST_LITTLE_ENDIAN - return swapBytes (value); -#else - return value; -#endif -} - -} - -#endif diff --git a/beast/Chrono.h b/beast/Chrono.h deleted file mode 100644 index 390ee11261..0000000000 --- a/beast/Chrono.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_CHRONO_H_INCLUDED -#define BEAST_CHRONO_H_INCLUDED - -#include -#include -#include -#include -#include - -#include - -#endif diff --git a/beast/Config.h b/beast/Config.h deleted file mode 100644 index aade217659..0000000000 --- a/beast/Config.h +++ /dev/null @@ -1,60 +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_CONFIG_H_INCLUDED -#define BEAST_CONFIG_H_INCLUDED - -// VFALCO NOTE this is analogous to - -#if !defined(BEAST_COMPILER_CONFIG) && !defined(BEAST_NO_COMPILER_CONFIG) && !defined(BEAST_NO_CONFIG) -#include -#endif -#ifdef BEAST_COMPILER_CONFIG -#include BEAST_COMPILER_CONFIG -#endif - -#if !defined(BEAST_STDLIB_CONFIG) && !defined(BEAST_NO_STDLIB_CONFIG) && !defined(BEAST_NO_CONFIG) && defined(__cplusplus) -#include -#endif -#ifdef BEAST_STDLIB_CONFIG -#include BEAST_STDLIB_CONFIG -#endif - -#if !defined(BEAST_PLATFORM_CONFIG) && !defined(BEAST_NO_PLATFORM_CONFIG) && !defined(BEAST_NO_CONFIG) -#include -#endif -#ifdef BEAST_PLATFORM_CONFIG -#include BEAST_PLATFORM_CONFIG -#endif - -// Legacy -#include -#include -#include -#include -#include - -// Suffix -#include - -#endif diff --git a/beast/Crypto.h b/beast/Crypto.h deleted file mode 100644 index abd08124cd..0000000000 --- a/beast/Crypto.h +++ /dev/null @@ -1,26 +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_CRYPTO_H_INCLUDED -#define BEAST_CRYPTO_H_INCLUDED - -#include - -#endif - diff --git a/beast/HeapBlock.h b/beast/HeapBlock.h deleted file mode 100644 index 116f1f67d9..0000000000 --- a/beast/HeapBlock.h +++ /dev/null @@ -1,360 +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_HEAPBLOCK_H_INCLUDED -#define BEAST_HEAPBLOCK_H_INCLUDED - -#include -#include -#include - -#include - -// If the MSVC debug heap headers were included, disable -// the macros during the juce include since they conflict. -#ifdef _CRTDBG_MAP_ALLOC -#pragma push_macro("calloc") -#pragma push_macro("free") -#pragma push_macro("malloc") -#pragma push_macro("realloc") -#pragma push_macro("_recalloc") -#pragma push_macro("_aligned_free") -#pragma push_macro("_aligned_malloc") -#pragma push_macro("_aligned_offset_malloc") -#pragma push_macro("_aligned_realloc") -#pragma push_macro("_aligned_recalloc") -#pragma push_macro("_aligned_offset_realloc") -#pragma push_macro("_aligned_offset_recalloc") -#pragma push_macro("_aligned_msize") -#undef calloc -#undef free -#undef malloc -#undef realloc -#undef _recalloc -#undef _aligned_free -#undef _aligned_malloc -#undef _aligned_offset_malloc -#undef _aligned_realloc -#undef _aligned_recalloc -#undef _aligned_offset_realloc -#undef _aligned_offset_recalloc -#undef _aligned_msize -#endif - -namespace beast { - -#ifndef DOXYGEN -namespace HeapBlockHelper -{ - template - struct ThrowOnFail { static void check (void*) {} }; - - template<> - struct ThrowOnFail { static void check (void* data) { if (data == nullptr) throw std::bad_alloc(); } }; -} -#endif - -//============================================================================== -/** - Very simple container class to hold a pointer to some data on the heap. - - When you need to allocate some heap storage for something, always try to use - this class instead of allocating the memory directly using malloc/free. - - A HeapBlock object can be treated in pretty much exactly the same way - as an char*, but as long as you allocate it on the stack or as a class member, - it's almost impossible for it to leak memory. - - It also makes your code much more concise and readable than doing the same thing - using direct allocations, - - E.g. instead of this: - @code - int* temp = (int*) malloc (1024 * sizeof (int)); - memcpy (temp, xyz, 1024 * sizeof (int)); - free (temp); - temp = (int*) calloc (2048 * sizeof (int)); - temp[0] = 1234; - memcpy (foobar, temp, 2048 * sizeof (int)); - free (temp); - @endcode - - ..you could just write this: - @code - HeapBlock temp (1024); - memcpy (temp, xyz, 1024 * sizeof (int)); - temp.calloc (2048); - temp[0] = 1234; - memcpy (foobar, temp, 2048 * sizeof (int)); - @endcode - - The class is extremely lightweight, containing only a pointer to the - data, and exposes malloc/realloc/calloc/free methods that do the same jobs - as their less object-oriented counterparts. Despite adding safety, you probably - won't sacrifice any performance by using this in place of normal pointers. - - The throwOnFailure template parameter can be set to true if you'd like the class - to throw a std::bad_alloc exception when an allocation fails. If this is false, - then a failed allocation will just leave the heapblock with a null pointer (assuming - that the system's malloc() function doesn't throw). - - @see Array, MemoryBlock -*/ -template -class HeapBlock -{ -public: - //============================================================================== - /** Creates a HeapBlock which is initially just a null pointer. - - After creation, you can resize the array using the malloc(), calloc(), - or realloc() methods. - */ - HeapBlock() noexcept - : data (nullptr) - { - } - - /** Creates a HeapBlock containing a number of elements. - - The contents of the block are undefined, as it will have been created by a - malloc call. - - If you want an array of zero values, you can use the calloc() method or the - other constructor that takes an InitialisationState parameter. - */ - explicit HeapBlock (const size_t numElements) - : data (static_cast (std::malloc (numElements * sizeof (ElementType)))) - { - throwOnAllocationFailure(); - } - - /** Creates a HeapBlock containing a number of elements. - - The initialiseToZero parameter determines whether the new memory should be cleared, - or left uninitialised. - */ - HeapBlock (const size_t numElements, const bool initialiseToZero) - : data (static_cast (initialiseToZero - ? std::calloc (numElements, sizeof (ElementType)) - : std::malloc (numElements * sizeof (ElementType)))) - { - throwOnAllocationFailure(); - } - - - HeapBlock(HeapBlock const&) = delete; - HeapBlock& operator= (HeapBlock const&) = delete; - - /** Destructor. - This will free the data, if any has been allocated. - */ - ~HeapBlock() - { - std::free (data); - } - - #if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS - HeapBlock (HeapBlock&& other) noexcept - : data (other.data) - { - other.data = nullptr; - } - - HeapBlock& operator= (HeapBlock&& other) noexcept - { - std::swap (data, other.data); - return *this; - } - #endif - - //============================================================================== - /** Returns a raw pointer to the allocated data. - This may be a null pointer if the data hasn't yet been allocated, or if it has been - freed by calling the free() method. - */ - inline operator ElementType*() const noexcept { return data; } - - /** Returns a raw pointer to the allocated data. - This may be a null pointer if the data hasn't yet been allocated, or if it has been - freed by calling the free() method. - */ - inline ElementType* getData() const noexcept { return data; } - - /** Returns a void pointer to the allocated data. - This may be a null pointer if the data hasn't yet been allocated, or if it has been - freed by calling the free() method. - */ - inline operator void*() const noexcept { return static_cast (data); } - - /** Returns a void pointer to the allocated data. - This may be a null pointer if the data hasn't yet been allocated, or if it has been - freed by calling the free() method. - */ - inline operator const void*() const noexcept { return static_cast (data); } - - /** Lets you use indirect calls to the first element in the array. - Obviously this will cause problems if the array hasn't been initialised, because it'll - be referencing a null pointer. - */ - inline ElementType* operator->() const noexcept { return data; } - - /** Returns a reference to one of the data elements. - Obviously there's no bounds-checking here, as this object is just a dumb pointer and - has no idea of the size it currently has allocated. - */ - template - inline ElementType& operator[] (IndexType index) const noexcept { return data [index]; } - - /** Returns a pointer to a data element at an offset from the start of the array. - This is the same as doing pointer arithmetic on the raw pointer itself. - */ - template - inline ElementType* operator+ (IndexType index) const noexcept { return data + index; } - - //============================================================================== - /** Compares the pointer with another pointer. - This can be handy for checking whether this is a null pointer. - */ - inline bool operator== (const ElementType* const otherPointer) const noexcept { return otherPointer == data; } - - /** Compares the pointer with another pointer. - This can be handy for checking whether this is a null pointer. - */ - inline bool operator!= (const ElementType* const otherPointer) const noexcept { return otherPointer != data; } - - //============================================================================== - /** Allocates a specified amount of memory. - - This uses the normal malloc to allocate an amount of memory for this object. - Any previously allocated memory will be freed by this method. - - The number of bytes allocated will be (newNumElements * elementSize). Normally - you wouldn't need to specify the second parameter, but it can be handy if you need - to allocate a size in bytes rather than in terms of the number of elements. - - The data that is allocated will be freed when this object is deleted, or when you - call free() or any of the allocation methods. - */ - void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType)) - { - std::free (data); - data = static_cast (std::malloc (newNumElements * elementSize)); - throwOnAllocationFailure(); - } - - /** Allocates a specified amount of memory and clears it. - This does the same job as the malloc() method, but clears the memory that it allocates. - */ - void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType)) - { - std::free (data); - data = static_cast (std::calloc (newNumElements, elementSize)); - throwOnAllocationFailure(); - } - - /** Allocates a specified amount of memory and optionally clears it. - This does the same job as either malloc() or calloc(), depending on the - initialiseToZero parameter. - */ - void allocate (const size_t newNumElements, bool initialiseToZero) - { - std::free (data); - data = static_cast (initialiseToZero - ? std::calloc (newNumElements, sizeof (ElementType)) - : std::malloc (newNumElements * sizeof (ElementType))); - throwOnAllocationFailure(); - } - - /** Re-allocates a specified amount of memory. - - The semantics of this method are the same as malloc() and calloc(), but it - uses realloc() to keep as much of the existing data as possible. - */ - void reallocate (const size_t newNumElements, const size_t elementSize = sizeof (ElementType)) - { - data = static_cast (data == nullptr ? std::malloc (newNumElements * elementSize) - : std::realloc (data, newNumElements * elementSize)); - throwOnAllocationFailure(); - } - - /** Frees any currently-allocated data. - This will free the data and reset this object to be a null pointer. - */ - void free_up() - { - std::free (data); - data = nullptr; - } - - /** Swaps this object's data with the data of another HeapBlock. - The two objects simply exchange their data pointers. - */ - template - void swapWith (HeapBlock & other) noexcept - { - std::swap (data, other.data); - } - - /** This fills the block with zeros, up to the number of elements specified. - Since the block has no way of knowing its own size, you must make sure that the number of - elements you specify doesn't exceed the allocated size. - */ - void clear (size_t numElements) noexcept - { - zeromem (data, sizeof (ElementType) * numElements); - } - - /** This type alias can be used to get the type of the heapblock's elements. */ - using Type = ElementType; - -private: - //============================================================================== - ElementType* data; - - void throwOnAllocationFailure() const - { - HeapBlockHelper::ThrowOnFail::check (data); - } -}; - -} - -#ifdef _CRTDBG_MAP_ALLOC -#pragma pop_macro("_aligned_msize") -#pragma pop_macro("_aligned_offset_recalloc") -#pragma pop_macro("_aligned_offset_realloc") -#pragma pop_macro("_aligned_recalloc") -#pragma pop_macro("_aligned_realloc") -#pragma pop_macro("_aligned_offset_malloc") -#pragma pop_macro("_aligned_malloc") -#pragma pop_macro("_aligned_free") -#pragma pop_macro("_recalloc") -#pragma pop_macro("realloc") -#pragma pop_macro("malloc") -#pragma pop_macro("free") -#pragma pop_macro("calloc") -#endif - -#endif - diff --git a/beast/Insight.h b/beast/Insight.h deleted file mode 100644 index 25c456827f..0000000000 --- a/beast/Insight.h +++ /dev/null @@ -1,37 +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_INSIGHT_H_INCLUDED -#define BEAST_INSIGHT_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/beast/Intrusive.h b/beast/Intrusive.h deleted file mode 100644 index 2932453c5c..0000000000 --- a/beast/Intrusive.h +++ /dev/null @@ -1,26 +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_H_INCLUDED -#define BEAST_INTRUSIVE_H_INCLUDED - -#include -#include - -#endif diff --git a/beast/Memory.h b/beast/Memory.h deleted file mode 100644 index b9ae573b03..0000000000 --- a/beast/Memory.h +++ /dev/null @@ -1,81 +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_MEMORY_H_INCLUDED -#define BEAST_MEMORY_H_INCLUDED - -#include - -#include - -namespace beast { - -//============================================================================== -/** Fills a block of memory with zeros. */ -inline void zeromem (void* memory, size_t numBytes) noexcept - { memset (memory, 0, numBytes); } - -/** Overwrites a structure or object with zeros. */ -template -void zerostruct (Type& structure) noexcept - { memset (&structure, 0, sizeof (structure)); } - -//============================================================================== -#if BEAST_MAC || BEAST_IOS || DOXYGEN - - /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII. - You should use the BEAST_AUTORELEASEPOOL macro to create a local auto-release pool on the stack. - */ - class ScopedAutoReleasePool - { - public: - ScopedAutoReleasePool(); - ~ScopedAutoReleasePool(); - - - ScopedAutoReleasePool(ScopedAutoReleasePool const&) = delete; - ScopedAutoReleasePool& operator= (ScopedAutoReleasePool const&) = delete; - - private: - void* pool; - }; - - /** A macro that can be used to easily declare a local ScopedAutoReleasePool - object for RAII-based obj-C autoreleasing. - Because this may use the \@autoreleasepool syntax, you must follow the macro with - a set of braces to mark the scope of the pool. - */ -#if (BEAST_COMPILER_SUPPORTS_ARC && defined (__OBJC__)) || DOXYGEN - #define BEAST_AUTORELEASEPOOL @autoreleasepool -#else - #define BEAST_AUTORELEASEPOOL const beast::ScopedAutoReleasePool BEAST_JOIN_MACRO (autoReleasePool_, __LINE__); -#endif - -#else - #define BEAST_AUTORELEASEPOOL -#endif - -} - -#endif - diff --git a/beast/SmartPtr.h b/beast/SmartPtr.h deleted file mode 100644 index a76a5850c4..0000000000 --- a/beast/SmartPtr.h +++ /dev/null @@ -1,28 +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_SMARTPTR_H_INCLUDED -#define BEAST_SMARTPTR_H_INCLUDED - -#include - -#include -#include - -#endif diff --git a/beast/Threads.h b/beast/Threads.h deleted file mode 100644 index 62b1a8d776..0000000000 --- a/beast/Threads.h +++ /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. -*/ -//============================================================================== - -#ifndef BEAST_THREADS_H_INCLUDED -#define BEAST_THREADS_H_INCLUDED - -#include -#include -#include - -#include - -#endif diff --git a/beast/Version.h b/beast/Version.h deleted file mode 100644 index 468a0b0210..0000000000 --- a/beast/Version.h +++ /dev/null @@ -1,45 +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_VERSION_H_INCLUDED -#define BEAST_VERSION_H_INCLUDED - -#include - -/** Current BEAST version number. */ -unsigned int const BEAST_VERSION_MAJOR = 1; -unsigned int const BEAST_VERSION_MINOR = 0; -unsigned int const BEAST_VERSION_BUILD = 0; - -unsigned int const BEAST_VERSION = - (BEAST_VERSION_MAJOR << 16) + - (BEAST_VERSION_MINOR << 8) + - BEAST_VERSION_BUILD; - -inline -std::string -getBeastVersion() -{ - return "Beast v" + std::to_string (BEAST_VERSION_MAJOR) + - "." + std::to_string (BEAST_VERSION_MINOR) + - "." + std::to_string (BEAST_VERSION_BUILD); -} - -#endif - diff --git a/beast/asio/Asio.unity.cpp b/beast/asio/Asio.unity.cpp index fb6ff5ca27..6334a818ae 100644 --- a/beast/asio/Asio.unity.cpp +++ b/beast/asio/Asio.unity.cpp @@ -21,7 +21,6 @@ #include #endif -#include #include #include #include diff --git a/beast/asio/IPAddressConversion.h b/beast/asio/IPAddressConversion.h deleted file mode 100644 index 13572340bb..0000000000 --- a/beast/asio/IPAddressConversion.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_ASIO_IPADDRESSCONVERSION_H_INCLUDED -#define BEAST_ASIO_IPADDRESSCONVERSION_H_INCLUDED - -#include - -#include - -#include - -namespace beast { -namespace IP { - -/** Convert to Endpoint. - The port is set to zero. -*/ -Endpoint from_asio (boost::asio::ip::address const& address); - -/** Convert to Endpoint. */ -Endpoint from_asio (boost::asio::ip::tcp::endpoint const& endpoint); - -/** Convert to asio::ip::address. - The port is ignored. -*/ -boost::asio::ip::address to_asio_address (Endpoint const& endpoint); - -/** Convert to asio::ip::tcp::endpoint. */ -boost::asio::ip::tcp::endpoint to_asio_endpoint (Endpoint const& endpoint); - -} -} - -namespace beast { - -// DEPRECATED -struct IPAddressConversion -{ - static IP::Endpoint from_asio (boost::asio::ip::address const& address) - { return IP::from_asio (address); } - static IP::Endpoint from_asio (boost::asio::ip::tcp::endpoint const& endpoint) - { return IP::from_asio (endpoint); } - static boost::asio::ip::address to_asio_address (IP::Endpoint const& address) - { return IP::to_asio_address (address); } - static boost::asio::ip::tcp::endpoint to_asio_endpoint (IP::Endpoint const& address) - { return IP::to_asio_endpoint (address); } -}; - -} - -#endif diff --git a/beast/asio/README.md b/beast/asio/README.md deleted file mode 100644 index e503d62f5e..0000000000 --- a/beast/asio/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# beast::asio - -Wrappers and utilities to make working with boost::asio easier. - -## Rules for asynchronous objects - -If an object calls asynchronous initiating functions it must either: - - 1. Manage its lifetime by being reference counted - - or - - 2. Wait for all pending completion handlers to be called before - allowing itself to be destroyed. diff --git a/beast/asio/impl/IPAddressConversion.cpp b/beast/asio/impl/IPAddressConversion.cpp deleted file mode 100644 index 70f61c69ac..0000000000 --- a/beast/asio/impl/IPAddressConversion.cpp +++ /dev/null @@ -1,67 +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 - -namespace beast { -namespace IP { - -Endpoint from_asio (boost::asio::ip::address const& address) -{ - if (address.is_v4 ()) - { - boost::asio::ip::address_v4::bytes_type const bytes ( - address.to_v4().to_bytes()); - return Endpoint (AddressV4 ( - bytes [0], bytes [1], bytes [2], bytes [3])); - } - - // VFALCO TODO IPv6 support - assert(false); - return Endpoint(); -} - -Endpoint from_asio (boost::asio::ip::tcp::endpoint const& endpoint) -{ - return from_asio (endpoint.address()).at_port (endpoint.port()); -} - -boost::asio::ip::address to_asio_address (Endpoint const& endpoint) -{ - if (endpoint.address().is_v4()) - { - return boost::asio::ip::address ( - boost::asio::ip::address_v4 ( - endpoint.address().to_v4().value)); - } - - // VFALCO TODO IPv6 support - assert(false); - return boost::asio::ip::address ( - boost::asio::ip::address_v6 ()); -} - -boost::asio::ip::tcp::endpoint to_asio_endpoint (Endpoint const& endpoint) -{ - return boost::asio::ip::tcp::endpoint ( - to_asio_address (endpoint), endpoint.port()); -} - -} -} diff --git a/beast/asio/streambuf.h b/beast/asio/streambuf.h index b8ff63d184..6f7e5af767 100644 --- a/beast/asio/streambuf.h +++ b/beast/asio/streambuf.h @@ -20,7 +20,7 @@ #ifndef BEAST_ASIO_STREAMBUF_H_INCLUDED #define BEAST_ASIO_STREAMBUF_H_INCLUDED -#include +#include #include #include #include diff --git a/beast/asio/waitable_executor.h b/beast/asio/waitable_executor.h deleted file mode 100644 index 7695a8fa5d..0000000000 --- a/beast/asio/waitable_executor.h +++ /dev/null @@ -1,315 +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_ASIO_WAITABLE_EXECUTOR_H_INCLUDED -#define BEAST_ASIO_WAITABLE_EXECUTOR_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace asio { - -namespace detail { - -template -class waitable_executor_wrapped_handler -{ -private: - static_assert (std::is_same , Owner>::value, - "Owner cannot be a const or reference type"); - - Handler handler_; - std::reference_wrapper owner_; - bool cont_; - -public: - waitable_executor_wrapped_handler (Owner& owner, - Handler&& handler, bool continuation = false) - : handler_ (std::move(handler)) - , owner_ (owner) - { - using boost::asio::asio_handler_is_continuation; - cont_ = continuation ? true : - asio_handler_is_continuation( - std::addressof(handler_)); - owner_.get().increment(); - } - - waitable_executor_wrapped_handler (Owner& owner, - Handler const& handler, bool continuation = false) - : handler_ (handler) - , owner_ (owner) - { - using boost::asio::asio_handler_is_continuation; - cont_ = continuation ? true : - asio_handler_is_continuation( - std::addressof(handler_)); - owner_.get().increment(); - } - - ~waitable_executor_wrapped_handler() - { - owner_.get().decrement(); - } - - waitable_executor_wrapped_handler ( - waitable_executor_wrapped_handler const& other) - : handler_ (other.handler_) - , owner_ (other.owner_) - , cont_ (other.cont_) - { - owner_.get().increment(); - } - - waitable_executor_wrapped_handler ( - waitable_executor_wrapped_handler&& other) - : handler_ (std::move(other.handler_)) - , owner_ (other.owner_) - , cont_ (other.cont_) - { - owner_.get().increment(); - } - - waitable_executor_wrapped_handler& operator=( - waitable_executor_wrapped_handler const&) = delete; - - template - void - operator()(Args&&... args) - { - handler_(std::forward(args)...); - } - - template - void - operator()(Args&&... args) const - { - handler_(std::forward(args)...); - } - - template - friend - void - asio_handler_invoke (Function& f, - waitable_executor_wrapped_handler* h) - { - using boost::asio::asio_handler_invoke; - asio_handler_invoke(f, - std::addressof(h->handler_)); - } - - template - friend - void - asio_handler_invoke (Function const& f, - waitable_executor_wrapped_handler* h) - { - using boost::asio::asio_handler_invoke; - asio_handler_invoke(f, - std::addressof(h->handler_)); - } - - friend - void* - asio_handler_allocate (std::size_t size, - waitable_executor_wrapped_handler* h) - { - using boost::asio::asio_handler_allocate; - return asio_handler_allocate( - size, std::addressof(h->handler_)); - } - - friend - void - asio_handler_deallocate (void* p, std::size_t size, - waitable_executor_wrapped_handler* h) - { - using boost::asio::asio_handler_deallocate; - asio_handler_deallocate( - p, size, std::addressof(h->handler_)); - } - - friend - bool - asio_handler_is_continuation ( - waitable_executor_wrapped_handler* h) - { - return h->cont_; - } -}; - -} // detail - -//------------------------------------------------------------------------------ - -/** Executor which provides blocking until all handlers are called. */ -class waitable_executor -{ -private: - template - friend class detail::waitable_executor_wrapped_handler; - - std::mutex mutex_; - std::condition_variable cond_; - std::size_t count_ = 0; - std::vector> notify_; - -public: - /** Block until all handlers are called. */ - template - void - wait(); - - /** Blocks until all handlers are called or time elapses. - @return `true` if all handlers are done or `false` if the time elapses. - */ - template - bool - wait_for (std::chrono::duration< - Rep, Period> const& elapsed_time); - - /** Blocks until all handlers are called or a time is reached. - @return `true` if all handlers are done or `false` on timeout. - */ - template - bool - wait_until (std::chrono::time_point< - Clock, Duration> const& timeout_time); - - /** Call a function asynchronously after all handlers are called. - The function may be called on the callers thread. - */ - template - void - async_wait(std::function f); - - /** Create a new handler that dispatches the wrapped handler on the Context. */ - template - detail::waitable_executor_wrapped_handler> - wrap (Handler&& handler); - -private: - template - void - increment(); - - template - void - decrement(); -}; - -template -void -waitable_executor::wait() -{ - std::unique_lock lock(mutex_); - cond_.wait(lock, - [this]() { return count_ == 0; }); -} - -template -bool -waitable_executor::wait_for (std::chrono::duration< - Rep, Period> const& elapsed_time) -{ - std::unique_lock lock(mutex_); - return cond_.wait_for(lock, elapsed_time, - [this]() { return count_ == 0; }) == - std::cv_status::no_timeout; -} - -template -bool -waitable_executor::wait_until (std::chrono::time_point< - Clock, Duration> const& timeout_time) -{ - std::unique_lock lock(mutex_); - return cond_.wait_until(lock, timeout_time, - [this]() { return count_ == 0; }) == - std::cv_status::no_timeout; - return true; -} - -template -void -waitable_executor::async_wait(std::function f) -{ - bool busy; - { - std::lock_guard _(mutex_); - busy = count_ > 0; - if (busy) - notify_.emplace_back(std::move(f)); - } - if (! busy) - f(); -} - -template -detail::waitable_executor_wrapped_handler> -waitable_executor::wrap (Handler&& handler) -{ - return detail::waitable_executor_wrapped_handler< - waitable_executor, std::remove_reference_t>( - *this, std::forward(handler)); -} - -template -void -waitable_executor::increment() -{ - std::lock_guard _(mutex_); - ++count_; -} - -template -void -waitable_executor::decrement() -{ - bool notify; - std::vector> list; - { - std::lock_guard _(mutex_); - notify = --count_ == 0; - if (notify) - std::swap(list, notify_); - } - if (notify) - { - cond_.notify_all(); - for(auto& _ : list) - _(); - } -} - -} // asio -} // beast - -#endif diff --git a/beast/boost/Boost.unity.cpp b/beast/boost/Boost.unity.cpp deleted file mode 100644 index 042d7f2e20..0000000000 --- a/beast/boost/Boost.unity.cpp +++ /dev/null @@ -1,32 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include - -namespace detail { - -// to squelch linker warnings -int boostUnusedVariable = 0; - -} - diff --git a/beast/boost/ErrorCode.h b/beast/boost/ErrorCode.h deleted file mode 100644 index f87a157573..0000000000 --- a/beast/boost/ErrorCode.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_BOOST_ERRORCODE_H_INCLUDED -#define BEAST_BOOST_ERRORCODE_H_INCLUDED - -#include - -namespace beast { - -// Lift this into our namespace. For now we will -// use boost, and then switch to std::error_code when -// it is available on all our supported platforms. -// -using ErrorCode = boost::system::error_code; - -} - -#endif diff --git a/beast/chrono/Chrono.unity.cpp b/beast/chrono/Chrono.unity.cpp deleted file mode 100644 index 10460203fc..0000000000 --- a/beast/chrono/Chrono.unity.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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include - -#include - -#include -#include diff --git a/beast/chrono/RelativeTime.h b/beast/chrono/RelativeTime.h deleted file mode 100644 index abfc318b94..0000000000 --- a/beast/chrono/RelativeTime.h +++ /dev/null @@ -1,190 +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_CHRONO_RELATIVETIME_H_INCLUDED -#define BEAST_CHRONO_RELATIVETIME_H_INCLUDED - -#include - -#include -#include - -namespace beast { - -//============================================================================== -/** A relative measure of time. - - The time is stored as a number of seconds, at double-precision floating - point accuracy, and may be positive or negative. - - If you need an absolute time, (i.e. a date + time), see the Time class. -*/ -class RelativeTime -{ -public: - //============================================================================== - /** The underlying data type used by RelativeTime. - - If you need to get to the underlying time and manipulate it - you can use this to declare a type that is guaranteed to - work cleanly. - */ - using value_type = double; - - //============================================================================== - /** Creates a RelativeTime. - - @param seconds the number of seconds, which may be +ve or -ve. - @see milliseconds, minutes, hours, days, weeks - */ - explicit RelativeTime (value_type seconds = 0.0) noexcept; - - /** Copies another relative time. */ - RelativeTime (const RelativeTime& other) noexcept; - - /** Copies another relative time. */ - RelativeTime& operator= (const RelativeTime& other) noexcept; - - /** Destructor. */ - ~RelativeTime() noexcept; - - bool isZero() const - { return numSeconds == 0; } - - bool isNotZero() const - { return numSeconds != 0; } - - /** Returns the amount of time since the process was started. */ - static RelativeTime fromStartup (); - - //============================================================================== - /** Creates a new RelativeTime object representing a number of milliseconds. - @see seconds, minutes, hours, days, weeks - */ - static RelativeTime milliseconds (int milliseconds) noexcept; - - /** Creates a new RelativeTime object representing a number of milliseconds. - @see seconds, minutes, hours, days, weeks - */ - static RelativeTime milliseconds (std::int64_t milliseconds) noexcept; - - /** Creates a new RelativeTime object representing a number of seconds. - @see milliseconds, minutes, hours, days, weeks - */ - static RelativeTime seconds (value_type seconds) noexcept; - - /** Creates a new RelativeTime object representing a number of minutes. - @see milliseconds, hours, days, weeks - */ - static RelativeTime minutes (value_type numberOfMinutes) noexcept; - - /** Creates a new RelativeTime object representing a number of hours. - @see milliseconds, minutes, days, weeks - */ - static RelativeTime hours (value_type numberOfHours) noexcept; - - /** Creates a new RelativeTime object representing a number of days. - @see milliseconds, minutes, hours, weeks - */ - static RelativeTime days (value_type numberOfDays) noexcept; - - /** Creates a new RelativeTime object representing a number of weeks. - @see milliseconds, minutes, hours, days - */ - static RelativeTime weeks (value_type numberOfWeeks) noexcept; - - //============================================================================== - /** Returns the number of milliseconds this time represents. - @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks - */ - std::int64_t inMilliseconds() const noexcept; - - /** Returns the number of seconds this time represents. - @see inMilliseconds, inMinutes, inHours, inDays, inWeeks - */ - value_type inSeconds() const noexcept { return numSeconds; } - - /** Returns the number of minutes this time represents. - @see inMilliseconds, inSeconds, inHours, inDays, inWeeks - */ - value_type inMinutes() const noexcept; - - /** Returns the number of hours this time represents. - @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks - */ - value_type inHours() const noexcept; - - /** Returns the number of days this time represents. - @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks - */ - value_type inDays() const noexcept; - - /** Returns the number of weeks this time represents. - @see inMilliseconds, inSeconds, inMinutes, inHours, inDays - */ - value_type inWeeks() const noexcept; - - template - RelativeTime operator+ (Number seconds) const noexcept - { return RelativeTime (numSeconds + seconds); } - - template - RelativeTime operator- (Number seconds) const noexcept - { return RelativeTime (numSeconds - seconds); } - - /** Adds another RelativeTime to this one. */ - RelativeTime operator+= (RelativeTime timeToAdd) noexcept; - - /** Subtracts another RelativeTime from this one. */ - RelativeTime operator-= (RelativeTime timeToSubtract) noexcept; - - /** Adds a number of seconds to this time. */ - RelativeTime operator+= (value_type secondsToAdd) noexcept; - - /** Subtracts a number of seconds from this time. */ - RelativeTime operator-= (value_type secondsToSubtract) noexcept; - -private: - value_type numSeconds; -}; - -//------------------------------------------------------------------------------ - -bool operator== (RelativeTime t1, RelativeTime t2) noexcept; -bool operator!= (RelativeTime t1, RelativeTime t2) noexcept; -bool operator> (RelativeTime t1, RelativeTime t2) noexcept; -bool operator< (RelativeTime t1, RelativeTime t2) noexcept; -bool operator>= (RelativeTime t1, RelativeTime t2) noexcept; -bool operator<= (RelativeTime t1, RelativeTime t2) noexcept; - -//------------------------------------------------------------------------------ - -/** Adds two RelativeTimes together. */ -RelativeTime operator+ (RelativeTime t1, RelativeTime t2) noexcept; - -/** Subtracts two RelativeTimes. */ -RelativeTime operator- (RelativeTime t1, RelativeTime t2) noexcept; - -} - -#endif diff --git a/beast/chrono/impl/RelativeTime.cpp b/beast/chrono/impl/RelativeTime.cpp deleted file mode 100644 index 7e7664d259..0000000000 --- a/beast/chrono/impl/RelativeTime.cpp +++ /dev/null @@ -1,291 +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. -*/ -//============================================================================== - -#include - -namespace beast { - -RelativeTime::RelativeTime (const RelativeTime::value_type secs) noexcept - : numSeconds (secs) -{ -} - -RelativeTime::RelativeTime (const RelativeTime& other) noexcept - : numSeconds (other.numSeconds) -{ -} - -RelativeTime::~RelativeTime() noexcept {} - -//============================================================================== - -RelativeTime RelativeTime::milliseconds (const int milliseconds) noexcept -{ - return RelativeTime (milliseconds * 0.001); -} - -RelativeTime RelativeTime::milliseconds (const std::int64_t milliseconds) noexcept -{ - return RelativeTime (milliseconds * 0.001); -} - -RelativeTime RelativeTime::seconds (RelativeTime::value_type s) noexcept -{ - return RelativeTime (s); -} - -RelativeTime RelativeTime::minutes (const RelativeTime::value_type numberOfMinutes) noexcept -{ - return RelativeTime (numberOfMinutes * 60.0); -} - -RelativeTime RelativeTime::hours (const RelativeTime::value_type numberOfHours) noexcept -{ - return RelativeTime (numberOfHours * (60.0 * 60.0)); -} - -RelativeTime RelativeTime::days (const RelativeTime::value_type numberOfDays) noexcept -{ - return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); -} - -RelativeTime RelativeTime::weeks (const RelativeTime::value_type numberOfWeeks) noexcept -{ - return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); -} - -//============================================================================== - -std::int64_t RelativeTime::inMilliseconds() const noexcept -{ - return (std::int64_t) (numSeconds * 1000.0); -} - -RelativeTime::value_type RelativeTime::inMinutes() const noexcept -{ - return numSeconds / 60.0; -} - -RelativeTime::value_type RelativeTime::inHours() const noexcept -{ - return numSeconds / (60.0 * 60.0); -} - -RelativeTime::value_type RelativeTime::inDays() const noexcept -{ - return numSeconds / (60.0 * 60.0 * 24.0); -} - -RelativeTime::value_type RelativeTime::inWeeks() const noexcept -{ - return numSeconds / (60.0 * 60.0 * 24.0 * 7.0); -} - -//============================================================================== - -RelativeTime& RelativeTime::operator= (const RelativeTime& other) noexcept { numSeconds = other.numSeconds; return *this; } - -RelativeTime RelativeTime::operator+= (RelativeTime t) noexcept -{ - numSeconds += t.numSeconds; return *this; -} - -RelativeTime RelativeTime::operator-= (RelativeTime t) noexcept -{ - numSeconds -= t.numSeconds; return *this; -} - -RelativeTime RelativeTime::operator+= (const RelativeTime::value_type secs) noexcept -{ - numSeconds += secs; return *this; -} - -RelativeTime RelativeTime::operator-= (const RelativeTime::value_type secs) noexcept -{ - numSeconds -= secs; return *this; -} - -RelativeTime operator+ (RelativeTime t1, RelativeTime t2) noexcept -{ - return t1 += t2; -} - -RelativeTime operator- (RelativeTime t1, RelativeTime t2) noexcept -{ - return t1 -= t2; -} - -bool operator== (RelativeTime t1, RelativeTime t2) noexcept -{ - return t1.inSeconds() == t2.inSeconds(); -} - -bool operator!= (RelativeTime t1, RelativeTime t2) noexcept -{ - return t1.inSeconds() != t2.inSeconds(); -} - -bool operator> (RelativeTime t1, RelativeTime t2) noexcept -{ - return t1.inSeconds() > t2.inSeconds(); -} - -bool operator< (RelativeTime t1, RelativeTime t2) noexcept -{ - return t1.inSeconds() < t2.inSeconds(); -} - -bool operator>= (RelativeTime t1, RelativeTime t2) noexcept -{ - return t1.inSeconds() >= t2.inSeconds(); -} - -bool operator<= (RelativeTime t1, RelativeTime t2) noexcept -{ - return t1.inSeconds() <= t2.inSeconds(); -} - -} - -#if BEAST_WINDOWS - -#include - -namespace beast { -namespace detail { - -static double monotonicCurrentTimeInSeconds() -{ - return GetTickCount64() / 1000.0; -} - -} -} - -#elif BEAST_MAC || BEAST_IOS - -#include -#include - -namespace beast { -namespace detail { - -static double monotonicCurrentTimeInSeconds() -{ - struct StaticInitializer - { - StaticInitializer () - { - double numerator; - double denominator; - - mach_timebase_info_data_t timebase; - (void) mach_timebase_info (&timebase); - - if (timebase.numer % 1000000 == 0) - { - numerator = timebase.numer / 1000000.0; - denominator = timebase.denom * 1000.0; - } - else - { - numerator = timebase.numer; - // VFALCO NOTE I don't understand this code - //denominator = timebase.denom * (std::uint64_t) 1000000 * 1000.0; - denominator = timebase.denom * 1000000000.0; - } - - ratio = numerator / denominator; - } - - double ratio; - }; - - static StaticInitializer const data; - - return mach_absolute_time() * data.ratio; -} -} -} - -#else - -#include - -namespace beast { -namespace detail { - -static double monotonicCurrentTimeInSeconds() -{ - timespec t; - clock_gettime (CLOCK_MONOTONIC, &t); - return t.tv_sec + t.tv_nsec / 1000000000.0; -} - -} -} - -#endif - -namespace beast { -namespace detail { - -// Records and returns the time from process startup -static double getStartupTime() -{ - struct StaticInitializer - { - StaticInitializer () - { - when = detail::monotonicCurrentTimeInSeconds(); - } - - double when; - }; - - static StaticInitializer const data; - - return data.when; -} - -// Used to call getStartupTime as early as possible -struct StartupTimeStaticInitializer -{ - StartupTimeStaticInitializer () - { - getStartupTime(); - } -}; - -static StartupTimeStaticInitializer startupTimeStaticInitializer; - -} - -RelativeTime RelativeTime::fromStartup () -{ - return RelativeTime ( - detail::monotonicCurrentTimeInSeconds() - detail::getStartupTime()); -} - -} - diff --git a/beast/chrono/ratio_io.h b/beast/chrono/ratio_io.h deleted file mode 100644 index 1a86e4fe88..0000000000 --- a/beast/chrono/ratio_io.h +++ /dev/null @@ -1,622 +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. -*/ -//============================================================================== - -// ratio_io -// -// (C) Copyright Howard Hinnant -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). - -#ifndef BEAST_CHRONO_RATIO_IO_H_INCLUDED -#define BEAST_CHRONO_RATIO_IO_H_INCLUDED - -/* - - ratio_io synopsis - -#include -#include - -namespace std -{ - -template -struct ratio_string -{ - static basic_string symbol(); - static basic_string prefix(); -}; - -} // std - -*/ - -#include -#include -#include - -//_LIBCPP_BEGIN_NAMESPACE_STD -namespace std { - -template -struct ratio_string -{ - static basic_string<_CharT> symbol() {return prefix();} - static basic_string<_CharT> prefix(); -}; - -template -basic_string<_CharT> -ratio_string<_Ratio, _CharT>::prefix() -{ - basic_ostringstream<_CharT> __os; - __os << _CharT('[') << _Ratio::num << _CharT('/') - << _Ratio::den << _CharT(']'); - return __os.str(); -} - -// atto - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'a');} - static string prefix() {return string("atto");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'a');} - static u16string prefix() {return u16string(u"atto");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'a');} - static u32string prefix() {return u32string(U"atto");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'a');} - static wstring prefix() {return wstring(L"atto");} -}; - -// femto - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'f');} - static string prefix() {return string("femto");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'f');} - static u16string prefix() {return u16string(u"femto");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'f');} - static u32string prefix() {return u32string(U"femto");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'f');} - static wstring prefix() {return wstring(L"femto");} -}; - -// pico - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'p');} - static string prefix() {return string("pico");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'p');} - static u16string prefix() {return u16string(u"pico");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'p');} - static u32string prefix() {return u32string(U"pico");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'p');} - static wstring prefix() {return wstring(L"pico");} -}; - -// nano - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'n');} - static string prefix() {return string("nano");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'n');} - static u16string prefix() {return u16string(u"nano");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'n');} - static u32string prefix() {return u32string(U"nano");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'n');} - static wstring prefix() {return wstring(L"nano");} -}; - -// micro - -template <> -struct ratio_string -{ - static string symbol() {return string("\xC2\xB5");} - static string prefix() {return string("micro");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'\xB5');} - static u16string prefix() {return u16string(u"micro");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'\xB5');} - static u32string prefix() {return u32string(U"micro");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'\xB5');} - static wstring prefix() {return wstring(L"micro");} -}; - -// milli - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'm');} - static string prefix() {return string("milli");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'm');} - static u16string prefix() {return u16string(u"milli");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'm');} - static u32string prefix() {return u32string(U"milli");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'm');} - static wstring prefix() {return wstring(L"milli");} -}; - -// centi - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'c');} - static string prefix() {return string("centi");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'c');} - static u16string prefix() {return u16string(u"centi");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'c');} - static u32string prefix() {return u32string(U"centi");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'c');} - static wstring prefix() {return wstring(L"centi");} -}; - -// deci - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'd');} - static string prefix() {return string("deci");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'd');} - static u16string prefix() {return u16string(u"deci");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'd');} - static u32string prefix() {return u32string(U"deci");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'd');} - static wstring prefix() {return wstring(L"deci");} -}; - -// deca - -template <> -struct ratio_string -{ - static string symbol() {return string("da");} - static string prefix() {return string("deca");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(u"da");} - static u16string prefix() {return u16string(u"deca");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(U"da");} - static u32string prefix() {return u32string(U"deca");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(L"da");} - static wstring prefix() {return wstring(L"deca");} -}; - -// hecto - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'h');} - static string prefix() {return string("hecto");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'h');} - static u16string prefix() {return u16string(u"hecto");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'h');} - static u32string prefix() {return u32string(U"hecto");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'h');} - static wstring prefix() {return wstring(L"hecto");} -}; - -// kilo - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'k');} - static string prefix() {return string("kilo");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'k');} - static u16string prefix() {return u16string(u"kilo");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'k');} - static u32string prefix() {return u32string(U"kilo");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'k');} - static wstring prefix() {return wstring(L"kilo");} -}; - -// mega - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'M');} - static string prefix() {return string("mega");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'M');} - static u16string prefix() {return u16string(u"mega");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'M');} - static u32string prefix() {return u32string(U"mega");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'M');} - static wstring prefix() {return wstring(L"mega");} -}; - -// giga - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'G');} - static string prefix() {return string("giga");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'G');} - static u16string prefix() {return u16string(u"giga");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'G');} - static u32string prefix() {return u32string(U"giga");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'G');} - static wstring prefix() {return wstring(L"giga");} -}; - -// tera - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'T');} - static string prefix() {return string("tera");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'T');} - static u16string prefix() {return u16string(u"tera");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'T');} - static u32string prefix() {return u32string(U"tera");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'T');} - static wstring prefix() {return wstring(L"tera");} -}; - -// peta - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'P');} - static string prefix() {return string("peta");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'P');} - static u16string prefix() {return u16string(u"peta");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'P');} - static u32string prefix() {return u32string(U"peta");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'P');} - static wstring prefix() {return wstring(L"peta");} -}; - -// exa - -template <> -struct ratio_string -{ - static string symbol() {return string(1, 'E');} - static string prefix() {return string("exa");} -}; - -#if HAS_UNICODE_SUPPORT - -template <> -struct ratio_string -{ - static u16string symbol() {return u16string(1, u'E');} - static u16string prefix() {return u16string(u"exa");} -}; - -template <> -struct ratio_string -{ - static u32string symbol() {return u32string(1, U'E');} - static u32string prefix() {return u32string(U"exa");} -}; - -#endif - -template <> -struct ratio_string -{ - static wstring symbol() {return wstring(1, L'E');} - static wstring prefix() {return wstring(L"exa");} -}; - -//_LIBCPP_END_NAMESPACE_STD -} - -#endif // _RATIO_IO diff --git a/beast/utility/ci_char_traits.h b/beast/ci_char_traits.h similarity index 100% rename from beast/utility/ci_char_traits.h rename to beast/ci_char_traits.h diff --git a/beast/chrono/abstract_clock.h b/beast/clock/abstract_clock.h similarity index 100% rename from beast/chrono/abstract_clock.h rename to beast/clock/abstract_clock.h diff --git a/beast/chrono/basic_seconds_clock.h b/beast/clock/basic_seconds_clock.h similarity index 99% rename from beast/chrono/basic_seconds_clock.h rename to beast/clock/basic_seconds_clock.h index 8dbc47aec9..d2ce40db56 100644 --- a/beast/chrono/basic_seconds_clock.h +++ b/beast/clock/basic_seconds_clock.h @@ -20,7 +20,7 @@ #ifndef BEAST_CHRONO_BASIC_SECONDS_CLOCK_H_INCLUDED #define BEAST_CHRONO_BASIC_SECONDS_CLOCK_H_INCLUDED -#include +#include #include #include diff --git a/beast/chrono/chrono_util.h b/beast/clock/chrono_util.h similarity index 100% rename from beast/chrono/chrono_util.h rename to beast/clock/chrono_util.h diff --git a/beast/chrono/manual_clock.h b/beast/clock/manual_clock.h similarity index 98% rename from beast/chrono/manual_clock.h rename to beast/clock/manual_clock.h index c3652d330e..23b5165cd7 100644 --- a/beast/chrono/manual_clock.h +++ b/beast/clock/manual_clock.h @@ -20,7 +20,7 @@ #ifndef BEAST_CHRONO_MANUAL_CLOCK_H_INCLUDED #define BEAST_CHRONO_MANUAL_CLOCK_H_INCLUDED -#include +#include #include namespace beast { diff --git a/beast/chrono/tests/abstract_clock.test.cpp b/beast/clock/tests/beast_abstract_clock_test.cpp similarity index 97% rename from beast/chrono/tests/abstract_clock.test.cpp rename to beast/clock/tests/beast_abstract_clock_test.cpp index b508d0ed03..1487f8aa11 100644 --- a/beast/chrono/tests/abstract_clock.test.cpp +++ b/beast/clock/tests/beast_abstract_clock_test.cpp @@ -19,8 +19,8 @@ // MODULES: ../impl/chrono_io.cpp -#include -#include +#include +#include #include #include #include diff --git a/beast/chrono/tests/basic_seconds_clock.test.cpp b/beast/clock/tests/beast_basic_seconds_clock_test.cpp similarity index 96% rename from beast/chrono/tests/basic_seconds_clock.test.cpp rename to beast/clock/tests/beast_basic_seconds_clock_test.cpp index 6678d638ea..227aba5466 100644 --- a/beast/chrono/tests/basic_seconds_clock.test.cpp +++ b/beast/clock/tests/beast_basic_seconds_clock_test.cpp @@ -19,7 +19,7 @@ #include -#include +#include namespace beast { diff --git a/beast/config/CompilerConfig.h b/beast/config/CompilerConfig.h deleted file mode 100644 index b7ade9ade7..0000000000 --- a/beast/config/CompilerConfig.h +++ /dev/null @@ -1,151 +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_CONFIG_COMPILERCONFIG_H_INCLUDED -#define BEAST_CONFIG_COMPILERCONFIG_H_INCLUDED - -#include -#include - -// This file defines miscellaneous macros for debugging, assertions, etc. - -#if BEAST_FORCE_DEBUG -# undef BEAST_DEBUG -# define BEAST_DEBUG 1 -#endif - -/** This macro defines the C calling convention used as the standard for Beast calls. -*/ -#if BEAST_MSVC -# define BEAST_CDECL __cdecl -#else -# define BEAST_CDECL -#endif - -/** This macro fixes C++'s constexpr for VS2012, which doesn't understand it. -*/ -#if BEAST_MSVC -# define BEAST_CONSTEXPR const -#else -# define BEAST_CONSTEXPR constexpr -#endif - -//------------------------------------------------------------------------------ - -#if ! DOXYGEN - #define BEAST_JOIN_MACRO_HELPER(a, b) a ## b - #define BEAST_STRINGIFY_MACRO_HELPER(a) #a -#endif - -/** A good old-fashioned C macro concatenation helper. - This combines two items (which may themselves be macros) into a single string, - avoiding the pitfalls of the ## macro operator. -*/ -#define BEAST_JOIN_MACRO(item1, item2) BEAST_JOIN_MACRO_HELPER (item1, item2) - -/** A handy C macro for stringifying any symbol, rather than just a macro parameter. -*/ -#define BEAST_STRINGIFY(item) BEAST_STRINGIFY_MACRO_HELPER (item) - -//------------------------------------------------------------------------------ - -#if BEAST_MSVC || DOXYGEN -/** This can be placed before a stack or member variable declaration to tell - the compiler to align it to the specified number of bytes. -*/ -#define BEAST_ALIGN(bytes) __declspec (align (bytes)) -#else -#define BEAST_ALIGN(bytes) __attribute__ ((aligned (bytes))) -#endif - -//------------------------------------------------------------------------------ - -// Cross-compiler deprecation macros.. -#ifdef DOXYGEN - /** This macro can be used to wrap a function which has been deprecated. */ - #define BEAST_DEPRECATED(functionDef) -#elif BEAST_MSVC && ! BEAST_NO_DEPRECATION_WARNINGS - #define BEAST_DEPRECATED(functionDef) __declspec(deprecated) functionDef -#elif BEAST_GCC && ! BEAST_NO_DEPRECATION_WARNINGS - #define BEAST_DEPRECATED(functionDef) functionDef __attribute__ ((deprecated)) -#else - #define BEAST_DEPRECATED(functionDef) functionDef -#endif - -//------------------------------------------------------------------------------ - -#if BEAST_GCC -# define BEAST_PACKED __attribute__((packed)) -#elif ! DOXYGEN -# define BEAST_PACKED -#endif - -//------------------------------------------------------------------------------ - -// Here, we'll check for C++11 compiler support, and if it's not available, define -// a few workarounds, so that we can still use some of the newer language features. -#if defined (__GXX_EXPERIMENTAL_CXX0X__) && defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 405 -# define BEAST_COMPILER_SUPPORTS_NOEXCEPT 1 -# define BEAST_COMPILER_SUPPORTS_NULLPTR 1 -# define BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS 1 -# if (__GNUC__ * 100 + __GNUC_MINOR__) >= 407 && ! defined (BEAST_COMPILER_SUPPORTS_OVERRIDE_AND_FINAL) -# define BEAST_COMPILER_SUPPORTS_OVERRIDE_AND_FINAL 1 -# endif -#endif - -#if BEAST_CLANG && defined (__has_feature) -# if __has_feature (cxx_nullptr) -# define BEAST_COMPILER_SUPPORTS_NULLPTR 1 -# endif -# if __has_feature (cxx_noexcept) -# define BEAST_COMPILER_SUPPORTS_NOEXCEPT 1 -# endif -# if __has_feature (cxx_rvalue_references) -# define BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS 1 -# endif -# ifndef BEAST_COMPILER_SUPPORTS_OVERRIDE_AND_FINAL -# define BEAST_COMPILER_SUPPORTS_OVERRIDE_AND_FINAL 1 -# endif -# ifndef BEAST_COMPILER_SUPPORTS_ARC -# define BEAST_COMPILER_SUPPORTS_ARC 1 -# endif -#endif - -#if defined (_MSC_VER) && _MSC_VER >= 1600 -# define BEAST_COMPILER_SUPPORTS_NULLPTR 1 -# define BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS 1 -#endif - -#if defined (_MSC_VER) && _MSC_VER >= 1700 -# define BEAST_COMPILER_SUPPORTS_OVERRIDE_AND_FINAL 1 -#endif - -#if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS -# define BEAST_MOVE_ARG(type) type&& -# define BEAST_MOVE_CAST(type) static_cast -#else -# define BEAST_MOVE_ARG(type) type -# define BEAST_MOVE_CAST(type) type -#endif - -#endif diff --git a/beast/config/ConfigCheck.h b/beast/config/ConfigCheck.h deleted file mode 100644 index 3469ffbd06..0000000000 --- a/beast/config/ConfigCheck.h +++ /dev/null @@ -1,69 +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_CONFIG_CONFIGCHECK_H_INCLUDED -#define BEAST_CONFIG_CONFIGCHECK_H_INCLUDED - -// -// Apply sensible defaults for the configuration settings -// - -#ifndef BEAST_FORCE_DEBUG -#define BEAST_FORCE_DEBUG 0 -#endif - -#ifndef BEAST_LOG_ASSERTIONS -# if BEAST_ANDROID -# define BEAST_LOG_ASSERTIONS 1 -# else -# define BEAST_LOG_ASSERTIONS 0 -# endif -#endif - -#if BEAST_DEBUG && ! defined (BEAST_CHECK_MEMORY_LEAKS) -#define BEAST_CHECK_MEMORY_LEAKS 1 -#endif - -#ifndef BEAST_DISABLE_CONTRACT_CHECKS -#define BEAST_DISABLE_CONTRACT_CHECKS 0 -#endif - -//------------------------------------------------------------------------------ - -#ifndef BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES -#define BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES 0 -#endif - -#ifndef BEAST_INCLUDE_ZLIB_CODE -#define BEAST_INCLUDE_ZLIB_CODE 1 -#endif - -#ifndef BEAST_ZLIB_INCLUDE_PATH -#define BEAST_ZLIB_INCLUDE_PATH -#endif - -#ifndef BEAST_SQLITE_FORCE_NDEBUG -#define BEAST_SQLITE_FORCE_NDEBUG 0 -#endif - -#ifndef BEAST_STRING_UTF_TYPE -#define BEAST_STRING_UTF_TYPE 8 -#endif - -#endif diff --git a/beast/config/PlatformConfig.h b/beast/config/PlatformConfig.h deleted file mode 100644 index 12af9c889c..0000000000 --- a/beast/config/PlatformConfig.h +++ /dev/null @@ -1,211 +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_CONFIG_PLATFORMCONFIG_H_INCLUDED -#define BEAST_CONFIG_PLATFORMCONFIG_H_INCLUDED - -//============================================================================== -/* This file figures out which platform is being built, and defines some macros - that the rest of the code can use for OS-specific compilation. - - Macros that will be set here are: - - - One of BEAST_WINDOWS, BEAST_MAC BEAST_LINUX, BEAST_IOS, BEAST_ANDROID, etc. - - Either BEAST_32BIT or BEAST_64BIT, depending on the architecture. - - Either BEAST_LITTLE_ENDIAN or BEAST_BIG_ENDIAN. - - Either BEAST_INTEL or BEAST_PPC - - Either BEAST_GCC or BEAST_MSVC -*/ - -//============================================================================== -#if (defined (_WIN32) || defined (_WIN64)) - #define BEAST_WIN32 1 - #define BEAST_WINDOWS 1 -#elif defined (BEAST_ANDROID) - #undef BEAST_ANDROID - #define BEAST_ANDROID 1 -#elif defined (LINUX) || defined (__linux__) - #define BEAST_LINUX 1 -#elif defined (__APPLE_CPP__) || defined(__APPLE_CC__) - #define Point CarbonDummyPointName // (workaround to avoid definition of "Point" by old Carbon headers) - #define Component CarbonDummyCompName - #include // (needed to find out what platform we're using) - #undef Point - #undef Component - - #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR - #define BEAST_IPHONE 1 - #define BEAST_IOS 1 - #else - #define BEAST_MAC 1 - #endif -#elif defined (__FreeBSD__) - #define BEAST_BSD 1 -#else - #error "Unknown platform!" -#endif - -//============================================================================== -#if BEAST_WINDOWS - #ifdef _MSC_VER - #ifdef _WIN64 - #define BEAST_64BIT 1 - #else - #define BEAST_32BIT 1 - #endif - #endif - - #ifdef _DEBUG - #define BEAST_DEBUG 1 - #endif - - #ifdef __MINGW32__ - #define BEAST_MINGW 1 - #ifdef __MINGW64__ - #define BEAST_64BIT 1 - #else - #define BEAST_32BIT 1 - #endif - #endif - - /** If defined, this indicates that the processor is little-endian. */ - #define BEAST_LITTLE_ENDIAN 1 - - #define BEAST_INTEL 1 -#endif - -//============================================================================== -#if BEAST_MAC || BEAST_IOS - - #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG)) - #define BEAST_DEBUG 1 - #endif - - #ifdef __LITTLE_ENDIAN__ - #define BEAST_LITTLE_ENDIAN 1 - #else - #define BEAST_BIG_ENDIAN 1 - #endif -#endif - -#if BEAST_MAC - - #if defined (__ppc__) || defined (__ppc64__) - #define BEAST_PPC 1 - #elif defined (__arm__) - #define BEAST_ARM 1 - #else - #define BEAST_INTEL 1 - #endif - - #ifdef __LP64__ - #define BEAST_64BIT 1 - #else - #define BEAST_32BIT 1 - #endif - - #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4 - #error "Building for OSX 10.3 is no longer supported!" - #endif - - #ifndef MAC_OS_X_VERSION_10_5 - #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4" - #endif - -#endif - -//============================================================================== -#if BEAST_LINUX || BEAST_ANDROID || BEAST_BSD - - #ifdef _DEBUG - #define BEAST_DEBUG 1 - #endif - - // Allow override for big-endian Linux platforms - #if defined (__LITTLE_ENDIAN__) || ! defined (BEAST_BIG_ENDIAN) - #define BEAST_LITTLE_ENDIAN 1 - #undef BEAST_BIG_ENDIAN - #else - #undef BEAST_LITTLE_ENDIAN - #define BEAST_BIG_ENDIAN 1 - #endif - - #if defined (__LP64__) || defined (_LP64) - #define BEAST_64BIT 1 - #else - #define BEAST_32BIT 1 - #endif - - #if __MMX__ || __SSE__ || __amd64__ - #ifdef __arm__ - #define BEAST_ARM 1 - #else - #define BEAST_INTEL 1 - #endif - #endif -#endif - -//============================================================================== -// Compiler type macros. - -#ifdef __clang__ - #define BEAST_CLANG 1 -#elif defined (__GNUC__) - #define BEAST_GCC 1 -#elif defined (_MSC_VER) - #define BEAST_MSVC 1 - - #if _MSC_VER < 1500 - #define BEAST_VC8_OR_EARLIER 1 - - #if _MSC_VER < 1400 - #define BEAST_VC7_OR_EARLIER 1 - - #if _MSC_VER < 1300 - #warning "MSVC 6.0 is no longer supported!" - #endif - #endif - #endif - - #if BEAST_64BIT || ! BEAST_VC7_OR_EARLIER - #define BEAST_USE_INTRINSICS 1 - #endif -#else - #error unknown compiler -#endif - -//------------------------------------------------------------------------------ - -// Handy macro that lets pragma warnings be clicked in the output window -// -// Usage: #pragma message(BEAST_FILEANDLINE_ "Advertise here!") -// -// Note that a space following the macro is mandatory for C++11. -// -// This is here so it can be used in C compilations that include this directly. -// -#define BEAST_PP_STR2_(x) #x -#define BEAST_PP_STR1_(x) BEAST_PP_STR2_(x) -#define BEAST_FILEANDLINE_ __FILE__ "(" BEAST_PP_STR1_(__LINE__) "): warning:" - -#endif diff --git a/beast/config/SelectCompilerConfig.h b/beast/config/SelectCompilerConfig.h deleted file mode 100644 index 53d859a9c3..0000000000 --- a/beast/config/SelectCompilerConfig.h +++ /dev/null @@ -1,48 +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. -*/ -//============================================================================== - -// Ideas from boost - -// Intel -#ifndef BEAST_CONFIG_SELECTCOMPILERCONFIG_H_INCLUDED -#define BEAST_CONFIG_SELECTCOMPILERCONFIG_H_INCLUDED - -#if defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC) -#define BEAST_COMPILER_CONFIG "config/compiler/Intel.h" - -// Clang C++ emulates GCC, so it has to appear early. -#elif defined __clang__ -#define BEAST_COMPILER_CONFIG "config/compiler/Clang.h" - -// GNU C++: -#elif defined __GNUC__ -#define BEAST_COMPILER_CONFIG "config/compiler/Gcc.h" - -// Microsoft Visual C++ -// -// Must remain the last #elif since some other vendors (Metrowerks, for -// example) also #define _MSC_VER -#elif defined _MSC_VER -#define BEAST_COMPILER_CONFIG "config/compiler/VisualC.h" - -#else -#error "Unsupported compiler." -#endif - -#endif diff --git a/beast/config/SelectPlatformConfig.h b/beast/config/SelectPlatformConfig.h deleted file mode 100644 index 3f35fd4e60..0000000000 --- a/beast/config/SelectPlatformConfig.h +++ /dev/null @@ -1,48 +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. -*/ -//============================================================================== - -// Ideas from boost - -// Android, which must be manually set by defining BEAST_ANDROID -#ifndef BEAST_CONFIG_SELECTPLATFORMCONFIG_H_INCLUDED -#define BEAST_CONFIG_SELECTPLATFORMCONFIG_H_INCLUDED - -#if defined(BEAST_ANDROID) -#define BEAST_PLATFORM_CONFIG "config/platform/Android.h" - -// linux, also other platforms (Hurd etc) that use GLIBC -#elif (defined(linux) || defined(__linux) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__)) && !defined(_CRAYC) -#define BEAST_PLATFORM_CONFIG "config/platform/Linux.h" - -// BSD -#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) -#define BEAST_PLATFORM_CONFIG "config/platform/Bsd.h" - -// win32 -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(_WIN64) -#define BEAST_PLATFORM_CONFIG "config/platform/Win32.h" - -// MacOS -#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) || defined(__APPLE_CPP__) -#define BEAST_PLATFORM_CONFIG "config/platform/MacOS.h" - -#else -#error "Unsupported platform." -#endif -#endif diff --git a/beast/config/StandardConfig.h b/beast/config/StandardConfig.h deleted file mode 100644 index c2cb0cc1b2..0000000000 --- a/beast/config/StandardConfig.h +++ /dev/null @@ -1,77 +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_CONFIG_STANDARDCONFIG_H_INCLUDED -#define BEAST_CONFIG_STANDARDCONFIG_H_INCLUDED - -#ifndef BEAST_CONFIG_COMPILERCONFIG_H_INCLUDED -#error "CompilerConfig.h must be included first" -#endif - -// Now we'll include some common OS headers.. -#if BEAST_MSVC -#pragma warning (push) -#pragma warning (disable: 4514 4245 4100) -#endif - -#if BEAST_USE_INTRINSICS -#include -#endif - -#if BEAST_MAC || BEAST_IOS -#include -#endif - -#if BEAST_LINUX -#include -# if __INTEL_COMPILER -# if __ia64__ -#include -# else -#include -# endif -# endif -#endif - -#if BEAST_MSVC && BEAST_DEBUG -#include -#include -#include -#endif - -#if BEAST_MSVC -#pragma warning (pop) -#endif - -#if BEAST_ANDROID - #include - #include -#endif - -// undef symbols that are sometimes set by misguided 3rd-party headers.. -#undef check -#undef TYPE_BOOL -#undef max -#undef min - -#endif diff --git a/beast/config/Suffix.h b/beast/config/Suffix.h deleted file mode 100644 index 1a85d4b63e..0000000000 --- a/beast/config/Suffix.h +++ /dev/null @@ -1,25 +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_CONFIG_SUFFIX_H_INCLUDED -#define BEAST_CONFIG_SUFFIX_H_INCLUDED - -// Included at the end of Config.h - -#endif diff --git a/beast/config/compiler/VisualC.h b/beast/config/compiler/VisualC.h deleted file mode 100644 index e360cdd6b6..0000000000 --- a/beast/config/compiler/VisualC.h +++ /dev/null @@ -1,25 +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. -*/ -//============================================================================== - -// Microsoft Visual C++ compiler configuration - -#ifndef BEAST_CONFIG_COMPILER_VISUALC_H_INCLUDED -#define BEAST_CONFIG_COMPILER_VISUALC_H_INCLUDED - -#endif diff --git a/beast/config/platform/Android.h b/beast/config/platform/Android.h deleted file mode 100644 index 5d80ca2316..0000000000 --- a/beast/config/platform/Android.h +++ /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. -*/ -//============================================================================== - -// Android platform configuration - -#ifndef BEAST_CONFIG_PLATFORM_ANDROID_H_INCLUDED -#define BEAST_CONFIG_PLATFORM_ANDROID_H_INCLUDED - -#ifdef BEAST_ANDROID -#undef BEAST_ANDROID -#endif -#define BEAST_ANDROID 1 - -#endif diff --git a/beast/config/platform/Bsd.h b/beast/config/platform/Bsd.h deleted file mode 100644 index af96cfdba8..0000000000 --- a/beast/config/platform/Bsd.h +++ /dev/null @@ -1,20 +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. -*/ -//============================================================================== - -// BSD, FreeBSD platform configuration diff --git a/beast/config/platform/Linux.h b/beast/config/platform/Linux.h deleted file mode 100644 index 3d38e9164e..0000000000 --- a/beast/config/platform/Linux.h +++ /dev/null @@ -1,21 +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. -*/ -//============================================================================== - -// Linux-compatible platform configuration - diff --git a/beast/config/platform/MacOS.h b/beast/config/platform/MacOS.h deleted file mode 100644 index a9243f983a..0000000000 --- a/beast/config/platform/MacOS.h +++ /dev/null @@ -1,21 +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. -*/ -//============================================================================== - -// MacOS and iOS platform configuration - diff --git a/beast/config/platform/Win32.h b/beast/config/platform/Win32.h deleted file mode 100644 index 912613df4c..0000000000 --- a/beast/config/platform/Win32.h +++ /dev/null @@ -1,21 +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. -*/ -//============================================================================== - -// Win32 platform configuration - diff --git a/beast/container/Container.unity.cpp b/beast/container/Container.unity.cpp deleted file mode 100644 index e5bbf33cec..0000000000 --- a/beast/container/Container.unity.cpp +++ /dev/null @@ -1,24 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include diff --git a/beast/container/aged_container.h b/beast/container/aged_container.h deleted file mode 100644 index 726dbeb3ac..0000000000 --- a/beast/container/aged_container.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_CONTAINER_AGED_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_AGED_CONTAINER_H_INCLUDED - -#include - -namespace beast { - -template -struct is_aged_container - : std::false_type -{ -}; - -} - -#endif diff --git a/beast/container/aged_container_utility.h b/beast/container/aged_container_utility.h deleted file mode 100644 index 9ba44c6148..0000000000 --- a/beast/container/aged_container_utility.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_CONTAINER_AGED_CONTAINER_UTILITY_H_INCLUDED -#define BEAST_CONTAINER_AGED_CONTAINER_UTILITY_H_INCLUDED - -#include - -#include - -namespace beast { - -/** Expire aged container items past the specified age. */ -template -typename std::enable_if < - is_aged_container ::value, - std::size_t ->::type -expire (AgedContainer& c, std::chrono::duration const& age) -{ - std::size_t n (0); - auto const expired (c.clock().now() - age); - for (auto iter (c.chronological.cbegin()); - iter != c.chronological.cend() && - iter.when() <= expired;) - { - iter = c.erase (iter); - ++n; - } - return n; -} - -} - -#endif diff --git a/beast/container/aged_map.h b/beast/container/aged_map.h deleted file mode 100644 index 680aad49de..0000000000 --- a/beast/container/aged_map.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_CONTAINER_AGED_MAP_H_INCLUDED -#define BEAST_CONTAINER_AGED_MAP_H_INCLUDED - -#include - -#include -#include -#include - -namespace beast { - -template < - class Key, - class T, - class Clock = std::chrono::steady_clock, - class Compare = std::less , - class Allocator = std::allocator > -> -using aged_map = detail::aged_ordered_container < - false, true, Key, T, Clock, Compare, Allocator>; - -} - -#endif diff --git a/beast/container/aged_multimap.h b/beast/container/aged_multimap.h deleted file mode 100644 index 55807388fd..0000000000 --- a/beast/container/aged_multimap.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_CONTAINER_AGED_MULTIMAP_H_INCLUDED -#define BEAST_CONTAINER_AGED_MULTIMAP_H_INCLUDED - -#include - -#include -#include -#include - -namespace beast { - -template < - class Key, - class T, - class Clock = std::chrono::steady_clock, - class Compare = std::less , - class Allocator = std::allocator > -> -using aged_multimap = detail::aged_ordered_container < - true, true, Key, T, Clock, Compare, Allocator>; - -} - -#endif diff --git a/beast/container/aged_multiset.h b/beast/container/aged_multiset.h deleted file mode 100644 index aeb083fec2..0000000000 --- a/beast/container/aged_multiset.h +++ /dev/null @@ -1,42 +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_CONTAINER_AGED_MULTISET_H_INCLUDED -#define BEAST_CONTAINER_AGED_MULTISET_H_INCLUDED - -#include - -#include -#include -#include - -namespace beast { - -template < - class Key, - class Clock = std::chrono::steady_clock, - class Compare = std::less , - class Allocator = std::allocator -> -using aged_multiset = detail::aged_ordered_container < - true, false, Key, void, Clock, Compare, Allocator>; - -} - -#endif diff --git a/beast/container/aged_set.h b/beast/container/aged_set.h deleted file mode 100644 index 076e4830a4..0000000000 --- a/beast/container/aged_set.h +++ /dev/null @@ -1,42 +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_CONTAINER_AGED_SET_H_INCLUDED -#define BEAST_CONTAINER_AGED_SET_H_INCLUDED - -#include - -#include -#include -#include - -namespace beast { - -template < - class Key, - class Clock = std::chrono::steady_clock, - class Compare = std::less , - class Allocator = std::allocator -> -using aged_set = detail::aged_ordered_container < - false, false, Key, void, Clock, Compare, Allocator>; - -} - -#endif diff --git a/beast/container/aged_unordered_map.h b/beast/container/aged_unordered_map.h deleted file mode 100644 index b632312660..0000000000 --- a/beast/container/aged_unordered_map.h +++ /dev/null @@ -1,44 +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_CONTAINER_AGED_UNORDERED_MAP_H_INCLUDED -#define BEAST_CONTAINER_AGED_UNORDERED_MAP_H_INCLUDED - -#include - -#include -#include -#include - -namespace beast { - -template < - class Key, - class T, - class Clock = std::chrono::steady_clock, - class Hash = std::hash , - class KeyEqual = std::equal_to , - class Allocator = std::allocator > -> -using aged_unordered_map = detail::aged_unordered_container < - false, true, Key, T, Clock, Hash, KeyEqual, Allocator>; - -} - -#endif diff --git a/beast/container/aged_unordered_multimap.h b/beast/container/aged_unordered_multimap.h deleted file mode 100644 index c257700601..0000000000 --- a/beast/container/aged_unordered_multimap.h +++ /dev/null @@ -1,44 +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_CONTAINER_AGED_UNORDERED_MULTIMAP_H_INCLUDED -#define BEAST_CONTAINER_AGED_UNORDERED_MULTIMAP_H_INCLUDED - -#include - -#include -#include -#include - -namespace beast { - -template < - class Key, - class T, - class Clock = std::chrono::steady_clock, - class Hash = std::hash , - class KeyEqual = std::equal_to , - class Allocator = std::allocator > -> -using aged_unordered_multimap = detail::aged_unordered_container < - true, true, Key, T, Clock, Hash, KeyEqual, Allocator>; - -} - -#endif diff --git a/beast/container/aged_unordered_multiset.h b/beast/container/aged_unordered_multiset.h deleted file mode 100644 index 7d033cacc3..0000000000 --- a/beast/container/aged_unordered_multiset.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_CONTAINER_AGED_UNORDERED_MULTISET_H_INCLUDED -#define BEAST_CONTAINER_AGED_UNORDERED_MULTISET_H_INCLUDED - -#include - -#include -#include -#include - -namespace beast { - -template < - class Key, - class Clock = std::chrono::steady_clock, - class Hash = std::hash , - class KeyEqual = std::equal_to , - class Allocator = std::allocator -> -using aged_unordered_multiset = detail::aged_unordered_container < - true, false, Key, void, Clock, Hash, KeyEqual, Allocator>; - -} - -#endif diff --git a/beast/container/aged_unordered_set.h b/beast/container/aged_unordered_set.h deleted file mode 100644 index cf98970bb9..0000000000 --- a/beast/container/aged_unordered_set.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_CONTAINER_AGED_UNORDERED_SET_H_INCLUDED -#define BEAST_CONTAINER_AGED_UNORDERED_SET_H_INCLUDED - -#include - -#include -#include -#include - -namespace beast { - -template < - class Key, - class Clock = std::chrono::steady_clock, - class Hash = std::hash , - class KeyEqual = std::equal_to , - class Allocator = std::allocator -> -using aged_unordered_set = detail::aged_unordered_container < - false, false, Key, void, Clock, Hash, KeyEqual, Allocator>; - -} - -#endif diff --git a/beast/container/buffer_view.h b/beast/container/buffer_view.h deleted file mode 100644 index b61e8d703e..0000000000 --- a/beast/container/buffer_view.h +++ /dev/null @@ -1,520 +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_CONTAINER_BUFFER_VIEW_H_INCLUDED -#define BEAST_CONTAINER_BUFFER_VIEW_H_INCLUDED - -#include - -#include -#include // -#include -#include -#include -#include -#include -#include - -namespace beast { - -namespace detail { - -template >::value> -struct apply_const -{ - using type = U; -}; - -template -struct apply_const -{ - using type = const U; -}; - -// is_contiguous is true if C is a contiguous container -template -struct is_contiguous - : public std::false_type -{ -}; - -template -struct is_contiguous - : public is_contiguous -{ -}; - -template -struct is_contiguous > - : public std::true_type -{ -}; - -template -struct is_contiguous > - : public std::true_type -{ -}; - -template -struct is_contiguous > - : public std::true_type -{ -}; - -// True if T is const or U is not const -template -struct buffer_view_const_compatible : std::integral_constant ::value || ! std::is_const::value -> -{ -}; - -// True if T and U are the same or differ only in const, or -// if T and U are equally sized integral types. -template -struct buffer_view_ptr_compatible : std::integral_constant , std::remove_const >::value) || - (std::is_integral ::value && std::is_integral ::value && - sizeof (U) == sizeof (T)) -> -{ -}; - -// Determine if buffer_view is constructible from U* -template -struct buffer_view_convertible : std::integral_constant ::value && - buffer_view_ptr_compatible ::value -> -{ -}; - -// True if C is a container that can be used to construct a buffer_view -template -struct buffer_view_container_compatible : std::integral_constant ::value && buffer_view_convertible ::type>::value -> -{ -}; - -} // detail - -struct buffer_view_default_tag -{ -}; - -//------------------------------------------------------------------------------ - -/** A view into a range of contiguous container elements. - - The size of the view is determined at the time of construction. - This tries to emulate the interface of std::vector as closely as possible, - with the constraint that the size of the container cannot be changed. - - @tparam T The underlying element type. If T is const, member functions - which can modify elements are removed from the interface. - - @tparam Tag A type used to prevent two views with the same T from being - comparable or assignable. -*/ -template < - class T, - class Tag = buffer_view_default_tag -> -class buffer_view -{ -private: - T* m_base; - std::size_t m_size; - - static_assert (std::is_same >::value, - "T may not be a reference type"); - - static_assert (! std::is_same ::value, - "T may not be void"); - - static_assert (std::is_same , - std::remove_reference_t const>::value, - "Expected std::add_const to produce T const"); - - template - void - assign (Iter first, Iter last) noexcept - { - using U = typename std::iterator_traits ::value_type; - - static_assert (detail::buffer_view_const_compatible ::value, - "Cannot convert from 'U const' to 'T', " - "conversion loses const qualifiers"); - - static_assert (detail::buffer_view_ptr_compatible ::value, - "Cannot convert from 'U*' to 'T*, " - "types are incompatible"); - - if (first == last) - { - m_base = nullptr; - m_size = 0; - } - else - { - #if 0 - // fails on gcc - m_base = reinterpret_cast ( - std::addressof (*first)); - #else - m_base = reinterpret_cast (&*first); - #endif - m_size = std::distance (first, last); - } - } - -public: - using value_type = T; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - using reference = T&; - using const_reference = T const&; - using pointer = T*; - using const_pointer = T const*; - using iterator = T*; - using const_iterator = T const*; - using reverse_iterator = std::reverse_iterator ; - using const_reverse_iterator = std::reverse_iterator ; - - // default construct - buffer_view () noexcept - : m_base (nullptr) - , m_size (0) - { - } - - // copy construct - template ::value> - > - buffer_view (buffer_view v) noexcept - { - assign (v.begin(), v.end()); - } - - // construct from container - template ::value - > - > - buffer_view (C& c) noexcept - { - assign (c.begin(), c.end()); - } - - // construct from pointer range - template ::value> - > - buffer_view (U* first, U* last) noexcept - { - assign (first, last); - } - - // construct from base and size - template ::value> - > - buffer_view (U* u, std::size_t n) noexcept - : m_base (u) - , m_size (n) - { - } - - // assign from container - template ::value - > - > - buffer_view& - operator= (C& c) noexcept - { - assign (c.begin(), c.end()); - return *this; - } - - // - // Element access - // - - reference - at (size_type pos) - { - if (! (pos < size())) - throw std::out_of_range ("bad array index"); - return m_base [pos]; - } - - const_reference - at (size_type pos) const - { - if (! (pos < size())) - throw std::out_of_range ("bad array index"); - return m_base [pos]; - } - - reference - operator[] (size_type pos) noexcept - { - return m_base [pos]; - } - - const_reference - operator[] (size_type pos) const noexcept - { - return m_base [pos]; - } - - reference - back() noexcept - { - return m_base [m_size - 1]; - } - - const_reference - back() const noexcept - { - return m_base [m_size - 1]; - } - - reference - front() noexcept - { - return *m_base; - } - - const_reference - front() const noexcept - { - return *m_base; - } - - pointer - data() noexcept - { - return m_base; - } - - const_pointer - data() const noexcept - { - return m_base; - } - - // - // Iterators - // - - iterator - begin() noexcept - { - return m_base; - } - - const_iterator - begin() const noexcept - { - return m_base; - } - - const_iterator - cbegin() const noexcept - { - return m_base; - } - - iterator - end() noexcept - { - return m_base + m_size; - } - - const_iterator - end() const noexcept - { - return m_base + m_size; - } - - const_iterator - cend() const noexcept - { - return m_base + m_size; - } - - reverse_iterator - rbegin() noexcept - { - return reverse_iterator (end()); - } - - const_reverse_iterator - rbegin() const noexcept - { - return const_reverse_iterator (cend()); - } - - const_reverse_iterator - crbegin() const noexcept - { - return const_reverse_iterator (cend()); - } - - reverse_iterator - rend() noexcept - { - return reverse_iterator (begin()); - } - - const_reverse_iterator - rend() const noexcept - { - return const_reverse_iterator (cbegin()); - } - - const_reverse_iterator - crend() const noexcept - { - return const_reverse_iterator (cbegin()); - } - - // - // Capacity - // - - bool - empty() const noexcept - { - return m_size == 0; - } - - size_type - size() const noexcept - { - return m_size; - } - - size_type - max_size() const noexcept - { - return size(); - } - - size_type - capacity() const noexcept - { - return size(); - } - - // - // Modifiers - // - - template - friend void swap (buffer_view & lhs, - buffer_view & rhs) noexcept; -}; - -//------------------------------------------------------------------------------ - -template -inline -bool -operator== (buffer_view lhs, buffer_view rhs) -{ - return std::equal ( - lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()); -} - -template -inline -bool -operator!= (buffer_view lhs, buffer_view rhs) -{ - return ! (lhs == rhs); -} - -template -inline -bool -operator< (buffer_view lhs, buffer_view rhs) -{ - return std::lexicographical_compare ( - lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()); -} - -template -inline -bool -operator>= (buffer_view lhs, buffer_view rhs) -{ - return ! (lhs < rhs); -} - -template -inline -bool -operator> (buffer_view lhs, buffer_view rhs) -{ - return rhs < lhs; -} - -template -inline -bool -operator<= (buffer_view lhs, buffer_view rhs) -{ - return ! (rhs < lhs); -} - -template -inline -void -swap (buffer_view & lhs, buffer_view & rhs) noexcept -{ - std::swap (lhs.m_base, rhs.m_base); - std::swap (lhs.m_size, rhs.m_size); -} - -//------------------------------------------------------------------------------ - -template < - class T, - class Tag = buffer_view_default_tag -> -using const_buffer_view = buffer_view < - std::add_const_t , Tag>; - -} - -#endif diff --git a/beast/container/cyclic_iterator.h b/beast/container/cyclic_iterator.h deleted file mode 100644 index 167ced9b5b..0000000000 --- a/beast/container/cyclic_iterator.h +++ /dev/null @@ -1,513 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Based on work with these copyrights: - Copyright Carl Philipp Reh 2009 - 2013. - Copyright Philipp Middendorf 2009 - 2013. - Distributed under the Boost Software License, Version 1.0. - (See accompanying file LICENSE_1_0.txt or copy at - http://www.boost.org/LICENSE_1_0.txt) - - Original code taken from - https://github.com/freundlich/fcppt - - 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_CONTAINER_CYCLIC_ITERATOR_H_INCLUDED -#define BEAST_CONTAINER_CYCLIC_ITERATOR_H_INCLUDED - -#include -#include - -namespace beast { - -// -// cyclic_iterator_fwd.hpp -// - -template< - typename ContainerIterator -> -class cyclic_iterator; - -// -// cyclic_iterator_category.hpp -// - -namespace detail -{ - -template< - typename SourceCategory -> -struct cyclic_iterator_category; - -template<> -struct cyclic_iterator_category< - std::forward_iterator_tag -> -{ - using type = std::forward_iterator_tag; -}; - -template<> -struct cyclic_iterator_category< - std::bidirectional_iterator_tag -> -{ - using type = std::bidirectional_iterator_tag; -}; - -template<> -struct cyclic_iterator_category< - std::random_access_iterator_tag -> -{ - using type = std::bidirectional_iterator_tag; -}; - -} - -// -// cyclic_iterator_base.hpp -// - -namespace detail -{ - -template< - typename ContainerIterator -> -struct cyclic_iterator_base -{ - using type = boost::iterator_facade< - cyclic_iterator< - ContainerIterator - >, - typename std::iterator_traits< - ContainerIterator - >::value_type, - typename detail::cyclic_iterator_category< - typename std::iterator_traits< - ContainerIterator - >::iterator_category - >::type, - typename std::iterator_traits< - ContainerIterator - >::reference - >; -}; - -} - -// -// cyclic_iterator_decl.hpp -// - -/** -\brief An iterator adaptor that cycles through a range - -\ingroup fcpptmain - -\tparam ContainerIterator The underlying iterator which must be at least a -forward iterator - -A cyclic iterator can be useful in cases where you want end() to -become begin() again. For example, imagine a cycling through a -list of items which means if you skip over the last, you will return to the -first one. - -This class can only increment or decrement its underlying iterator, random -access is not supported. The iterator category will be at most bidirectional. -It inherits all capabilities from boost::iterator_facade which -means that it will have the usual iterator operations with their semantics. - -Here is a short example demonstrating its use. - -\snippet cyclic_iterator.cpp cyclic_iterator -*/ -template< - typename ContainerIterator -> -class cyclic_iterator -: - public detail::cyclic_iterator_base< - ContainerIterator - >::type -{ -public: - /** - \brief The base type which is a boost::iterator_facade - */ - using base_type = typename detail::cyclic_iterator_base< - ContainerIterator - >::type; - - /** - \brief The underlying iterator type - */ - using container_iterator_type = ContainerIterator; - - /** - \brief The value type adapted from \a ContainerIterator - */ - using value_type = typename base_type::value_type; - - /** - \brief The reference type adapted from \a ContainerIterator - */ - using reference = typename base_type::reference; - - /** - \brief The pointer type adapted from \a ContainerIterator - */ - using pointer = typename base_type::pointer; - - /** - \brief The difference type adapted from \a ContainerIterator - */ - using difference_type = typename base_type::difference_type; - - /** - \brief The iterator category, either Forward or Bidirectional - */ - using iterator_category = typename base_type::iterator_category; - - /** - \brief Creates a singular iterator - */ - cyclic_iterator(); - - /** - \brief Copy constructs from another cyclic iterator - - Copy constructs from another cyclic iterator \a other. This only works - if the underlying iterators are convertible. - - \param other The iterator to copy construct from - */ - template< - typename OtherIterator - > - explicit - cyclic_iterator( - cyclic_iterator const &other - ); - - /** - \brief Constructs a new cyclic iterator - - Constructs a new cyclic iterator, starting at \a it, inside - a range from \a begin to \a end. - - \param pos The start of the iterator - \param begin The beginning of the range - \param end The end of the range - - \warning The behaviour is undefined if \a pos isn't between \a begin - and \a end. Also, the behaviour is undefined, if \a begin and \a end - don't form a valid range. - */ - cyclic_iterator( - container_iterator_type const &pos, - container_iterator_type const &begin, - container_iterator_type const &end - ); - - /** - \brief Assigns from another cyclic iterator - - Assigns from another cyclic iterator \a other. This only works if the - underlying iterators are convertible. - - \param other The iterator to assign from - - \return *this - */ - template< - typename OtherIterator - > - cyclic_iterator & - operator=( - cyclic_iterator const &other - ); - - /** - \brief Returns the beginning of the range - */ - container_iterator_type - begin() const; - - /** - \brief Returns the end of the range - */ - container_iterator_type - end() const; - - /** - \brief Returns the underlying iterator - */ - container_iterator_type - get() const; -private: - friend class boost::iterator_core_access; - - void - increment(); - - void - decrement(); - - bool - equal( - cyclic_iterator const & - ) const; - - reference - dereference() const; - - difference_type - distance_to( - cyclic_iterator const & - ) const; -private: - container_iterator_type - it_, - begin_, - end_; -}; - -// -// cyclic_iterator_impl.hpp -// - -template< - typename ContainerIterator -> -cyclic_iterator< - ContainerIterator ->::cyclic_iterator() -: - it_(), - begin_(), - end_() -{ -} - -template< - typename ContainerIterator -> -template< - typename OtherIterator -> -cyclic_iterator< - ContainerIterator ->::cyclic_iterator( - cyclic_iterator< - OtherIterator - > const &_other -) -: - it_( - _other.it_ - ), - begin_( - _other.begin_ - ), - end_( - _other.end_ - ) -{ -} - -template< - typename ContainerIterator -> -cyclic_iterator< - ContainerIterator ->::cyclic_iterator( - container_iterator_type const &_it, - container_iterator_type const &_begin, - container_iterator_type const &_end -) -: - it_( - _it - ), - begin_( - _begin - ), - end_( - _end - ) -{ -} - -template< - typename ContainerIterator -> -template< - typename OtherIterator -> -cyclic_iterator< - ContainerIterator -> & -cyclic_iterator< - ContainerIterator ->::operator=( - cyclic_iterator< - OtherIterator - > const &_other -) -{ - it_ = _other.it_; - - begin_ = _other.begin_; - - end_ = _other.end_; - - return *this; -} - -template< - typename ContainerIterator -> -typename cyclic_iterator< - ContainerIterator ->::container_iterator_type -cyclic_iterator< - ContainerIterator ->::begin() const -{ - return begin_; -} - -template< - typename ContainerIterator -> -typename cyclic_iterator< - ContainerIterator ->::container_iterator_type -cyclic_iterator< - ContainerIterator ->::end() const -{ - return end_; -} - -template< - typename ContainerIterator -> -typename cyclic_iterator< - ContainerIterator ->::container_iterator_type -cyclic_iterator< - ContainerIterator ->::get() const -{ - return it_; -} - -template< - typename ContainerIterator -> -void -cyclic_iterator< - ContainerIterator ->::increment() -{ - if( - begin_ != end_ - && ++it_ == end_ - ) - it_ = begin_; -} - -template< - typename ContainerIterator -> -void -cyclic_iterator< - ContainerIterator ->::decrement() -{ - if( - begin_ == end_ - ) - return; - - if( - it_ == begin_ - ) - it_ = - std::prev( - end_ - ); - else - --it_; -} - -template< - typename ContainerIterator -> -bool -cyclic_iterator< - ContainerIterator ->::equal( - cyclic_iterator const &_other -) const -{ - return it_ == _other.it; -} - -template< - typename ContainerIterator -> -typename cyclic_iterator< - ContainerIterator ->::reference -cyclic_iterator< - ContainerIterator ->::dereference() const -{ - return *it_; -} - -template< - typename ContainerIterator -> -typename cyclic_iterator< - ContainerIterator ->::difference_type -cyclic_iterator< - ContainerIterator ->::distance_to( - cyclic_iterator const &_other -) const -{ - return _other.it_ - it_; -} - -// Convenience function for template argument deduction -template -cyclic_iterator make_cyclic ( - ContainerIterator const& pos, - ContainerIterator const& begin, - ContainerIterator const& end); -} - -#endif diff --git a/beast/container/detail/aged_associative_container.h b/beast/container/detail/aged_associative_container.h deleted file mode 100644 index 752fc140ce..0000000000 --- a/beast/container/detail/aged_associative_container.h +++ /dev/null @@ -1,54 +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_CONTAINER_DETAIL_AGED_ASSOCIATIVE_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_AGED_ASSOCIATIVE_CONTAINER_H_INCLUDED - -#include - -namespace beast { -namespace detail { - -// Extracts the key portion of value -template -struct aged_associative_container_extract_t -{ - template - decltype (Value::first) const& - operator() (Value const& value) const - { - return value.first; - } -}; - -template <> -struct aged_associative_container_extract_t -{ - template - Value const& - operator() (Value const& value) const - { - return value; - } -}; - -} -} - -#endif diff --git a/beast/container/detail/aged_container_iterator.h b/beast/container/detail/aged_container_iterator.h deleted file mode 100644 index b849f4ade9..0000000000 --- a/beast/container/detail/aged_container_iterator.h +++ /dev/null @@ -1,182 +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_CONTAINER_DETAIL_AGED_CONTAINER_ITERATOR_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_AGED_CONTAINER_ITERATOR_H_INCLUDED - -#include -#include - -namespace beast { - -template -class aged_ordered_container; - -namespace detail { - -// Idea for Base template argument to prevent having to repeat -// the base class declaration comes from newbiz on ##c++/Freenode -// -// If Iterator is SCARY then this iterator will be as well. -template < - bool is_const, - class Iterator, - class Base = - std::iterator < - typename std::iterator_traits ::iterator_category, - typename std::conditional ::type, - typename std::iterator_traits ::difference_type> -> -class aged_container_iterator - : public Base -{ -public: - using time_point = typename Iterator::value_type::stashed::time_point; - - // Could be '= default', but Visual Studio 2013 chokes on it [Aug 2014] - aged_container_iterator () - { - } - - // copy constructor - aged_container_iterator ( - aged_container_iterator - const& other) = default; - - // Disable constructing a const_iterator from a non-const_iterator. - // Converting between reverse and non-reverse iterators should be explicit. - template ::value == false>::type> - explicit aged_container_iterator (aged_container_iterator < - other_is_const, OtherIterator, OtherBase> const& other) - : m_iter (other.m_iter) - { - } - - // Disable constructing a const_iterator from a non-const_iterator. - template ::type> - aged_container_iterator (aged_container_iterator < - other_is_const, Iterator, OtherBase> const& other) - : m_iter (other.m_iter) - { - } - - // Disable assigning a const_iterator to a non-const iterator - template - auto - operator= (aged_container_iterator < - other_is_const, OtherIterator, OtherBase> const& other) -> - typename std::enable_if < - other_is_const == false || is_const == true, - aged_container_iterator&>::type - { - m_iter = other.m_iter; - return *this; - } - - template - bool operator== (aged_container_iterator < - other_is_const, OtherIterator, OtherBase> const& other) const - { - return m_iter == other.m_iter; - } - - template - bool operator!= (aged_container_iterator < - other_is_const, OtherIterator, OtherBase> const& other) const - { - return m_iter != other.m_iter; - } - - aged_container_iterator& operator++ () - { - ++m_iter; - return *this; - } - - aged_container_iterator operator++ (int) - { - aged_container_iterator const prev (*this); - ++m_iter; - return prev; - } - - aged_container_iterator& operator-- () - { - --m_iter; - return *this; - } - - aged_container_iterator operator-- (int) - { - aged_container_iterator const prev (*this); - --m_iter; - return prev; - } - - typename Base::reference operator* () const - { - return m_iter->value; - } - - typename Base::pointer operator-> () const - { - return &m_iter->value; - } - - time_point const& when () const - { - return m_iter->when; - } - -private: - template - friend class aged_ordered_container; - - template - friend class aged_unordered_container; - - template - friend class aged_container_iterator; - - template - aged_container_iterator (OtherIterator const& iter) - : m_iter (iter) - { - } - - Iterator const& iterator() const - { - return m_iter; - } - - Iterator m_iter; -}; - -} - -} - -#endif diff --git a/beast/container/detail/aged_ordered_container.h b/beast/container/detail/aged_ordered_container.h deleted file mode 100644 index 4ebb64d532..0000000000 --- a/beast/container/detail/aged_ordered_container.h +++ /dev/null @@ -1,1969 +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_CONTAINER_DETAIL_AGED_ORDERED_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_AGED_ORDERED_CONTAINER_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace detail { - -// Traits templates used to discern reverse_iterators, which are disallowed -// for mutating operations. -template -struct is_boost_reverse_iterator - : std::false_type -{}; - -#if BOOST_VERSION >= 105800 -template -struct is_boost_reverse_iterator> - : std::true_type -{}; -#else -template -struct is_boost_reverse_iterator> - : std::true_type -{}; -#endif - -/** Associative container where each element is also indexed by time. - - This container mirrors the interface of the standard library ordered - associative containers, with the addition that each element is associated - with a `when` `time_point` which is obtained from the value of the clock's - `now`. The function `touch` updates the time for an element to the current - time as reported by the clock. - - An extra set of iterator types and member functions are provided in the - `chronological` memberspace that allow traversal in temporal or reverse - temporal order. This container is useful as a building block for caches - whose items expire after a certain amount of time. The chronological - iterators allow for fully customizable expiration strategies. - - @see aged_set, aged_multiset, aged_map, aged_multimap -*/ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock = std::chrono::steady_clock, - class Compare = std::less , - class Allocator = std::allocator < - typename std::conditional , - Key>::type> -> -class aged_ordered_container -{ -public: - using clock_type = abstract_clock; - using time_point = typename clock_type::time_point; - using duration = typename clock_type::duration; - using key_type = Key; - using mapped_type = T; - using value_type = typename std::conditional < - IsMap, std::pair , Key>::type; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - - // Introspection (for unit tests) - using is_unordered = std::false_type; - using is_multi = std::integral_constant ; - using is_map = std::integral_constant ; - -private: - static Key const& extract (value_type const& value) - { - return aged_associative_container_extract_t () (value); - } - - // VFALCO TODO hoist to remove template argument dependencies - struct element - : boost::intrusive::set_base_hook < - boost::intrusive::link_mode < - boost::intrusive::normal_link> - > - , boost::intrusive::list_base_hook < - boost::intrusive::link_mode < - boost::intrusive::normal_link> - > - { - // Stash types here so the iterator doesn't - // need to see the container declaration. - struct stashed - { - using value_type = typename aged_ordered_container::value_type; - using time_point = typename aged_ordered_container::time_point; - }; - - element ( - time_point const& when_, - value_type const& value_) - : value (value_) - , when (when_) - { - } - - element ( - time_point const& when_, - value_type&& value_) - : value (std::move (value_)) - , when (when_) - { - } - - template < - class... Args, - class = typename std::enable_if < - std::is_constructible ::value>::type - > - element (time_point const& when_, Args&&... args) - : value (std::forward (args)...) - , when (when_) - { - } - - value_type value; - time_point when; - }; - - // VFALCO TODO This should only be enabled for maps. - class pair_value_compare - : private empty_base_optimization - , public std::binary_function - { - public: - bool operator() (value_type const& lhs, value_type const& rhs) const - { - return this->member() (lhs.first, rhs.first); - } - - pair_value_compare () - { - } - - pair_value_compare (pair_value_compare const& other) - : empty_base_optimization (other) - { - } - - private: - friend aged_ordered_container; - - pair_value_compare (Compare const& compare) - : empty_base_optimization (compare) - { - } - }; - - // Compares value_type against element, used in insert_check - // VFALCO TODO hoist to remove template argument dependencies - class KeyValueCompare - : private empty_base_optimization - , public std::binary_function - { - public: - KeyValueCompare () = default; - - KeyValueCompare (Compare const& compare) - : empty_base_optimization (compare) - { - } - - // VFALCO NOTE WE might want only to enable these overloads - // if Compare has is_transparent -#if 0 - template - bool operator() (K const& k, element const& e) const - { - return this->member() (k, extract (e.value)); - } - - template - bool operator() (element const& e, K const& k) const - { - return this->member() (extract (e.value), k); - } -#endif - - bool operator() (Key const& k, element const& e) const - { - return this->member() (k, extract (e.value)); - } - - bool operator() (element const& e, Key const& k) const - { - return this->member() (extract (e.value), k); - } - - bool operator() (element const& x, element const& y) const - { - return this->member() (extract (x.value), extract (y.value)); - } - - Compare& compare() - { - return empty_base_optimization ::member(); - } - - Compare const& compare() const - { - return empty_base_optimization ::member(); - } - }; - - using list_type = typename boost::intrusive::make_list >::type; - - using cont_type = typename std::conditional < - IsMulti, - typename boost::intrusive::make_multiset , - boost::intrusive::compare - >::type, - typename boost::intrusive::make_set , - boost::intrusive::compare - >::type - >::type; - - using ElementAllocator = typename std::allocator_traits < - Allocator>::template rebind_alloc ; - - using ElementAllocatorTraits = std::allocator_traits ; - - class config_t - : private KeyValueCompare - , private empty_base_optimization - { - public: - explicit config_t ( - clock_type& clock_) - : clock (clock_) - { - } - - config_t ( - clock_type& clock_, - Compare const& comp) - : KeyValueCompare (comp) - , clock (clock_) - { - } - - config_t ( - clock_type& clock_, - Allocator const& alloc_) - : empty_base_optimization (alloc_) - , clock (clock_) - { - } - - config_t ( - clock_type& clock_, - Compare const& comp, - Allocator const& alloc_) - : KeyValueCompare (comp) - , empty_base_optimization (alloc_) - , clock (clock_) - { - } - - config_t (config_t const& other) - : KeyValueCompare (other.key_compare()) - , empty_base_optimization ( - ElementAllocatorTraits:: - select_on_container_copy_construction ( - other.alloc())) - , clock (other.clock) - { - } - - config_t (config_t const& other, Allocator const& alloc) - : KeyValueCompare (other.key_compare()) - , empty_base_optimization (alloc) - , clock (other.clock) - { - } - - config_t (config_t&& other) - : KeyValueCompare (std::move (other.key_compare())) - , empty_base_optimization ( - std::move (other)) - , clock (other.clock) - { - } - - config_t (config_t&& other, Allocator const& alloc) - : KeyValueCompare (std::move (other.key_compare())) - , empty_base_optimization (alloc) - , clock (other.clock) - { - } - - config_t& operator= (config_t const& other) - { - if (this != &other) - { - compare() = other.compare(); - alloc() = other.alloc(); - clock = other.clock; - } - return *this; - } - - config_t& operator= (config_t&& other) - { - compare() = std::move (other.compare()); - alloc() = std::move (other.alloc()); - clock = other.clock; - return *this; - } - - Compare& compare () - { - return KeyValueCompare::compare(); - } - - Compare const& compare () const - { - return KeyValueCompare::compare(); - } - - KeyValueCompare& key_compare() - { - return *this; - } - - KeyValueCompare const& key_compare() const - { - return *this; - } - - ElementAllocator& alloc() - { - return empty_base_optimization < - ElementAllocator>::member(); - } - - ElementAllocator const& alloc() const - { - return empty_base_optimization < - ElementAllocator>::member(); - } - - std::reference_wrapper clock; - }; - - template - element* new_element (Args&&... args) - { - struct Deleter - { - std::reference_wrapper a_; - Deleter (ElementAllocator& a) - : a_(a) - { - } - - void - operator()(element* p) - { - ElementAllocatorTraits::deallocate (a_.get(), p, 1); - } - }; - - std::unique_ptr p (ElementAllocatorTraits::allocate ( - m_config.alloc(), 1), Deleter(m_config.alloc())); - ElementAllocatorTraits::construct (m_config.alloc(), - p.get(), clock().now(), std::forward (args)...); - return p.release(); - } - - void delete_element (element const* p) - { - ElementAllocatorTraits::destroy (m_config.alloc(), p); - ElementAllocatorTraits::deallocate ( - m_config.alloc(), const_cast(p), 1); - } - - void unlink_and_delete_element (element const* p) - { - chronological.list.erase ( - chronological.list.iterator_to (*p)); - m_cont.erase (m_cont.iterator_to (*p)); - delete_element (p); - } - -public: - using key_compare = Compare; - using value_compare = typename std::conditional < - IsMap, - pair_value_compare, - Compare>::type; - using allocator_type = Allocator; - using reference = value_type&; - using const_reference = value_type const&; - using pointer = typename std::allocator_traits < - Allocator>::pointer; - using const_pointer = typename std::allocator_traits < - Allocator>::const_pointer; - - // A set iterator (IsMap==false) is always const - // because the elements of a set are immutable. - using iterator = detail::aged_container_iterator< - ! IsMap, typename cont_type::iterator>; - using const_iterator = detail::aged_container_iterator< - true, typename cont_type::iterator>; - using reverse_iterator = detail::aged_container_iterator< - ! IsMap, typename cont_type::reverse_iterator>; - using const_reverse_iterator = detail::aged_container_iterator< - true, typename cont_type::reverse_iterator>; - - //-------------------------------------------------------------------------- - // - // Chronological ordered iterators - // - // "Memberspace" - // http://accu.org/index.php/journals/1527 - // - //-------------------------------------------------------------------------- - - class chronological_t - { - public: - // A set iterator (IsMap==false) is always const - // because the elements of a set are immutable. - using iterator = detail::aged_container_iterator< - ! IsMap, typename list_type::iterator>; - using const_iterator = detail::aged_container_iterator< - true, typename list_type::iterator>; - using reverse_iterator = detail::aged_container_iterator< - ! IsMap, typename list_type::reverse_iterator>; - using const_reverse_iterator = detail::aged_container_iterator< - true, typename list_type::reverse_iterator>; - - iterator begin () - { - return iterator (list.begin()); - } - - const_iterator begin () const - { - return const_iterator (list.begin ()); - } - - const_iterator cbegin() const - { - return const_iterator (list.begin ()); - } - - iterator end () - { - return iterator (list.end ()); - } - - const_iterator end () const - { - return const_iterator (list.end ()); - } - - const_iterator cend () const - { - return const_iterator (list.end ()); - } - - reverse_iterator rbegin () - { - return reverse_iterator (list.rbegin()); - } - - const_reverse_iterator rbegin () const - { - return const_reverse_iterator (list.rbegin ()); - } - - const_reverse_iterator crbegin() const - { - return const_reverse_iterator (list.rbegin ()); - } - - reverse_iterator rend () - { - return reverse_iterator (list.rend ()); - } - - const_reverse_iterator rend () const - { - return const_reverse_iterator (list.rend ()); - } - - const_reverse_iterator crend () const - { - return const_reverse_iterator (list.rend ()); - } - - iterator iterator_to (value_type& value) - { - static_assert (std::is_standard_layout ::value, - "must be standard layout"); - return list.iterator_to (*reinterpret_cast ( - reinterpret_cast(&value)-((std::size_t) - std::addressof(((element*)0)->member)))); - } - - const_iterator iterator_to (value_type const& value) const - { - static_assert (std::is_standard_layout ::value, - "must be standard layout"); - return list.iterator_to (*reinterpret_cast ( - reinterpret_cast(&value)-((std::size_t) - std::addressof(((element*)0)->member)))); - } - - private: - chronological_t () - { - } - - chronological_t (chronological_t const&) = delete; - chronological_t (chronological_t&&) = delete; - - friend class aged_ordered_container; - list_type mutable list; - } chronological; - - //-------------------------------------------------------------------------- - // - // Construction - // - //-------------------------------------------------------------------------- - - aged_ordered_container() = delete; - - explicit aged_ordered_container (clock_type& clock); - - aged_ordered_container (clock_type& clock, - Compare const& comp); - - aged_ordered_container (clock_type& clock, - Allocator const& alloc); - - aged_ordered_container (clock_type& clock, - Compare const& comp, Allocator const& alloc); - - template - aged_ordered_container (InputIt first, InputIt last, clock_type& clock); - - template - aged_ordered_container (InputIt first, InputIt last, clock_type& clock, - Compare const& comp); - - template - aged_ordered_container (InputIt first, InputIt last, clock_type& clock, - Allocator const& alloc); - - template - aged_ordered_container (InputIt first, InputIt last, clock_type& clock, - Compare const& comp, Allocator const& alloc); - - aged_ordered_container (aged_ordered_container const& other); - - aged_ordered_container (aged_ordered_container const& other, - Allocator const& alloc); - - aged_ordered_container (aged_ordered_container&& other); - - aged_ordered_container (aged_ordered_container&& other, - Allocator const& alloc); - - aged_ordered_container (std::initializer_list init, - clock_type& clock); - - aged_ordered_container (std::initializer_list init, - clock_type& clock, Compare const& comp); - - aged_ordered_container (std::initializer_list init, - clock_type& clock, Allocator const& alloc); - - aged_ordered_container (std::initializer_list init, - clock_type& clock, Compare const& comp, Allocator const& alloc); - - ~aged_ordered_container(); - - aged_ordered_container& - operator= (aged_ordered_container const& other); - - aged_ordered_container& - operator= (aged_ordered_container&& other); - - aged_ordered_container& - operator= (std::initializer_list init); - - allocator_type - get_allocator() const - { - return m_config.alloc(); - } - - clock_type& - clock() - { - return m_config.clock; - } - - clock_type const& - clock() const - { - return m_config.clock; - } - - //-------------------------------------------------------------------------- - // - // Element access (maps) - // - //-------------------------------------------------------------------------- - - template < - class K, - bool maybe_multi = IsMulti, - bool maybe_map = IsMap, - class = typename std::enable_if ::type> - typename std::conditional ::type& - at (K const& k); - - template < - class K, - bool maybe_multi = IsMulti, - bool maybe_map = IsMap, - class = typename std::enable_if ::type> - typename std::conditional ::type const& - at (K const& k) const; - - template < - bool maybe_multi = IsMulti, - bool maybe_map = IsMap, - class = typename std::enable_if ::type> - typename std::conditional ::type& - operator[] (Key const& key); - - template < - bool maybe_multi = IsMulti, - bool maybe_map = IsMap, - class = typename std::enable_if ::type> - typename std::conditional ::type& - operator[] (Key&& key); - - //-------------------------------------------------------------------------- - // - // Iterators - // - //-------------------------------------------------------------------------- - - iterator - begin () - { - return iterator (m_cont.begin()); - } - - const_iterator - begin () const - { - return const_iterator (m_cont.begin ()); - } - - const_iterator - cbegin() const - { - return const_iterator (m_cont.begin ()); - } - - iterator - end () - { - return iterator (m_cont.end ()); - } - - const_iterator - end () const - { - return const_iterator (m_cont.end ()); - } - - const_iterator - cend () const - { - return const_iterator (m_cont.end ()); - } - - reverse_iterator - rbegin () - { - return reverse_iterator (m_cont.rbegin()); - } - - const_reverse_iterator - rbegin () const - { - return const_reverse_iterator (m_cont.rbegin ()); - } - - const_reverse_iterator - crbegin() const - { - return const_reverse_iterator (m_cont.rbegin ()); - } - - reverse_iterator - rend () - { - return reverse_iterator (m_cont.rend ()); - } - - const_reverse_iterator - rend () const - { - return const_reverse_iterator (m_cont.rend ()); - } - - const_reverse_iterator - crend () const - { - return const_reverse_iterator (m_cont.rend ()); - } - - iterator - iterator_to (value_type& value) - { - static_assert (std::is_standard_layout ::value, - "must be standard layout"); - return m_cont.iterator_to (*reinterpret_cast ( - reinterpret_cast(&value)-((std::size_t) - std::addressof(((element*)0)->member)))); - } - - const_iterator - iterator_to (value_type const& value) const - { - static_assert (std::is_standard_layout ::value, - "must be standard layout"); - return m_cont.iterator_to (*reinterpret_cast ( - reinterpret_cast(&value)-((std::size_t) - std::addressof(((element*)0)->member)))); - } - - //-------------------------------------------------------------------------- - // - // Capacity - // - //-------------------------------------------------------------------------- - - bool - empty() const noexcept - { - return m_cont.empty(); - } - - size_type - size() const noexcept - { - return m_cont.size(); - } - - size_type - max_size() const noexcept - { - return m_config.max_size(); - } - - //-------------------------------------------------------------------------- - // - // Modifiers - // - //-------------------------------------------------------------------------- - - void - clear(); - - // map, set - template - auto - insert (value_type const& value) -> - typename std::enable_if >::type; - - // multimap, multiset - template - auto - insert (value_type const& value) -> - typename std::enable_if ::type; - - // set - template - auto - insert (value_type&& value) -> - typename std::enable_if >::type; - - // multiset - template - auto - insert (value_type&& value) -> - typename std::enable_if ::type; - - //--- - - // map, set - template - auto - insert (const_iterator hint, value_type const& value) -> - typename std::enable_if ::type; - - // multimap, multiset - template - typename std::enable_if ::type - insert (const_iterator /*hint*/, value_type const& value) - { - // VFALCO TODO Figure out how to utilize 'hint' - return insert (value); - } - - // map, set - template - auto - insert (const_iterator hint, value_type&& value) -> - typename std::enable_if ::type; - - // multimap, multiset - template - typename std::enable_if ::type - insert (const_iterator /*hint*/, value_type&& value) - { - // VFALCO TODO Figure out how to utilize 'hint' - return insert (std::move (value)); - } - - // map, multimap - template < - class P, - bool maybe_map = IsMap - > - typename std::enable_if ::value, - typename std::conditional - >::type - >::type - insert (P&& value) - { - return emplace (std::forward

(value)); - } - - // map, multimap - template < - class P, - bool maybe_map = IsMap - > - typename std::enable_if ::value, - typename std::conditional - >::type - >::type - insert (const_iterator hint, P&& value) - { - return emplace_hint (hint, std::forward

(value)); - } - - template - void - insert (InputIt first, InputIt last) - { - for (; first != last; ++first) - insert (cend(), *first); - } - - void - insert (std::initializer_list init) - { - insert (init.begin(), init.end()); - } - - // map, set - template - auto - emplace (Args&&... args) -> - typename std::enable_if >::type; - - // multiset, multimap - template - auto - emplace (Args&&... args) -> - typename std::enable_if ::type; - - // map, set - template - auto - emplace_hint (const_iterator hint, Args&&... args) -> - typename std::enable_if >::type; - - // multiset, multimap - template - typename std::enable_if ::type - emplace_hint (const_iterator /*hint*/, Args&&... args) - { - // VFALCO TODO Figure out how to utilize 'hint' - return emplace ( - std::forward (args)...); - } - - // enable_if prevents erase (reverse_iterator pos) from compiling - template ::value>> - detail::aged_container_iterator - erase (detail::aged_container_iterator pos); - - // enable_if prevents erase (reverse_iterator first, reverse_iterator last) - // from compiling - template ::value>> - detail::aged_container_iterator - erase (detail::aged_container_iterator first, - detail::aged_container_iterator last); - - template - auto - erase (K const& k) -> - size_type; - - void - swap (aged_ordered_container& other) noexcept; - - //-------------------------------------------------------------------------- - - // enable_if prevents touch (reverse_iterator pos) from compiling - template ::value>> - void - touch (detail::aged_container_iterator pos) - { - touch (pos, clock().now()); - } - - template - size_type - touch (K const& k); - - //-------------------------------------------------------------------------- - // - // Lookup - // - //-------------------------------------------------------------------------- - - // VFALCO TODO Respect is_transparent (c++14) - template - size_type - count (K const& k) const - { - return m_cont.count (k, - std::cref (m_config.key_compare())); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - iterator - find (K const& k) - { - return iterator (m_cont.find (k, - std::cref (m_config.key_compare()))); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - const_iterator - find (K const& k) const - { - return const_iterator (m_cont.find (k, - std::cref (m_config.key_compare()))); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - std::pair - equal_range (K const& k) - { - auto const r (m_cont.equal_range (k, - std::cref (m_config.key_compare()))); - return std::make_pair (iterator (r.first), - iterator (r.second)); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - std::pair - equal_range (K const& k) const - { - auto const r (m_cont.equal_range (k, - std::cref (m_config.key_compare()))); - return std::make_pair (const_iterator (r.first), - const_iterator (r.second)); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - iterator - lower_bound (K const& k) - { - return iterator (m_cont.lower_bound (k, - std::cref (m_config.key_compare()))); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - const_iterator - lower_bound (K const& k) const - { - return const_iterator (m_cont.lower_bound (k, - std::cref (m_config.key_compare()))); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - iterator - upper_bound (K const& k) - { - return iterator (m_cont.upper_bound (k, - std::cref (m_config.key_compare()))); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - const_iterator - upper_bound (K const& k) const - { - return const_iterator (m_cont.upper_bound (k, - std::cref (m_config.key_compare()))); - } - - //-------------------------------------------------------------------------- - // - // Observers - // - //-------------------------------------------------------------------------- - - key_compare - key_comp() const - { - return m_config.compare(); - } - - // VFALCO TODO Should this return const reference for set? - value_compare - value_comp() const - { - return value_compare (m_config.compare()); - } - - //-------------------------------------------------------------------------- - // - // Comparison - // - //-------------------------------------------------------------------------- - - // This differs from the standard in that the comparison - // is only done on the key portion of the value type, ignoring - // the mapped type. - // - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator - > - bool - operator== ( - aged_ordered_container const& other) const; - - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator - > - bool - operator!= ( - aged_ordered_container const& other) const - { - return ! (this->operator== (other)); - } - - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator - > - bool - operator< ( - aged_ordered_container const& other) const - { - value_compare const comp (value_comp ()); - return std::lexicographical_compare ( - cbegin(), cend(), other.cbegin(), other.cend(), comp); - } - - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator - > - bool - operator<= ( - aged_ordered_container const& other) const - { - return ! (other < *this); - } - - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator - > - bool - operator> ( - aged_ordered_container const& other) const - { - return other < *this; - } - - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherT, - class OtherDuration, - class OtherAllocator - > - bool - operator>= ( - aged_ordered_container const& other) const - { - return ! (*this < other); - } - -private: - // enable_if prevents erase (reverse_iterator pos, now) from compiling - template ::value>> - void - touch (detail::aged_container_iterator < - is_const, Iterator, Base> pos, - typename clock_type::time_point const& now); - - template ::propagate_on_container_swap::value> - typename std::enable_if ::type - swap_data (aged_ordered_container& other) noexcept; - - template ::propagate_on_container_swap::value> - typename std::enable_if ::type - swap_data (aged_ordered_container& other) noexcept; - -private: - config_t m_config; - cont_type mutable m_cont; -}; - -//------------------------------------------------------------------------------ - -template -aged_ordered_container :: -aged_ordered_container ( - clock_type& clock) - : m_config (clock) -{ -} - -template -aged_ordered_container :: -aged_ordered_container ( - clock_type& clock, - Compare const& comp) - : m_config (clock, comp) - , m_cont (comp) -{ -} - -template -aged_ordered_container :: -aged_ordered_container ( - clock_type& clock, - Allocator const& alloc) - : m_config (clock, alloc) -{ -} - -template -aged_ordered_container :: -aged_ordered_container ( - clock_type& clock, - Compare const& comp, - Allocator const& alloc) - : m_config (clock, comp, alloc) - , m_cont (comp) -{ -} - -template -template -aged_ordered_container :: -aged_ordered_container (InputIt first, InputIt last, - clock_type& clock) - : m_config (clock) -{ - insert (first, last); -} - -template -template -aged_ordered_container :: -aged_ordered_container (InputIt first, InputIt last, - clock_type& clock, - Compare const& comp) - : m_config (clock, comp) - , m_cont (comp) -{ - insert (first, last); -} - -template -template -aged_ordered_container :: -aged_ordered_container (InputIt first, InputIt last, - clock_type& clock, - Allocator const& alloc) - : m_config (clock, alloc) -{ - insert (first, last); -} - -template -template -aged_ordered_container :: -aged_ordered_container (InputIt first, InputIt last, - clock_type& clock, - Compare const& comp, - Allocator const& alloc) - : m_config (clock, comp, alloc) - , m_cont (comp) -{ - insert (first, last); -} - -template -aged_ordered_container :: -aged_ordered_container (aged_ordered_container const& other) - : m_config (other.m_config) - , m_cont (other.m_cont.comp()) -{ - insert (other.cbegin(), other.cend()); -} - -template -aged_ordered_container :: -aged_ordered_container (aged_ordered_container const& other, - Allocator const& alloc) - : m_config (other.m_config, alloc) - , m_cont (other.m_cont.comp()) -{ - insert (other.cbegin(), other.cend()); -} - -template -aged_ordered_container :: -aged_ordered_container (aged_ordered_container&& other) - : m_config (std::move (other.m_config)) - , m_cont (std::move (other.m_cont)) -{ - chronological.list = std::move (other.chronological.list); -} - -template -aged_ordered_container :: -aged_ordered_container (aged_ordered_container&& other, - Allocator const& alloc) - : m_config (std::move (other.m_config), alloc) - , m_cont (std::move(other.m_cont.comp())) -{ - insert (other.cbegin(), other.cend()); - other.clear (); -} - -template -aged_ordered_container :: -aged_ordered_container (std::initializer_list init, - clock_type& clock) - : m_config (clock) -{ - insert (init.begin(), init.end()); -} - -template -aged_ordered_container :: -aged_ordered_container (std::initializer_list init, - clock_type& clock, - Compare const& comp) - : m_config (clock, comp) - , m_cont (comp) -{ - insert (init.begin(), init.end()); -} - -template -aged_ordered_container :: -aged_ordered_container (std::initializer_list init, - clock_type& clock, - Allocator const& alloc) - : m_config (clock, alloc) -{ - insert (init.begin(), init.end()); -} - -template -aged_ordered_container :: -aged_ordered_container (std::initializer_list init, - clock_type& clock, - Compare const& comp, - Allocator const& alloc) - : m_config (clock, comp, alloc) - , m_cont (comp) -{ - insert (init.begin(), init.end()); -} - -template -aged_ordered_container :: -~aged_ordered_container() -{ - clear(); -} - -template -auto -aged_ordered_container :: -operator= (aged_ordered_container const& other) -> - aged_ordered_container& -{ - if (this != &other) - { - clear(); - this->m_config = other.m_config; - insert (other.begin(), other.end()); - } - return *this; -} - -template -auto -aged_ordered_container :: -operator= (aged_ordered_container&& other) -> - aged_ordered_container& -{ - clear(); - this->m_config = std::move (other.m_config); - insert (other.begin(), other.end()); - other.clear(); - return *this; -} - -template -auto -aged_ordered_container :: -operator= (std::initializer_list init) -> - aged_ordered_container& -{ - clear (); - insert (init); - return *this; -} - -//------------------------------------------------------------------------------ - -template -template -typename std::conditional ::type& -aged_ordered_container :: -at (K const& k) -{ - auto const iter (m_cont.find (k, - std::cref (m_config.key_compare()))); - if (iter == m_cont.end()) - throw std::out_of_range ("key not found"); - return iter->value.second; -} - -template -template -typename std::conditional ::type const& -aged_ordered_container :: -at (K const& k) const -{ - auto const iter (m_cont.find (k, - std::cref (m_config.key_compare()))); - if (iter == m_cont.end()) - throw std::out_of_range ("key not found"); - return iter->value.second; -} - -template -template -typename std::conditional ::type& -aged_ordered_container :: -operator[] (Key const& key) -{ - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (key, - std::cref (m_config.key_compare()), d)); - if (result.second) - { - element* const p (new_element ( - std::piecewise_construct, std::forward_as_tuple (key), - std::forward_as_tuple ())); - m_cont.insert_commit (*p, d); - chronological.list.push_back (*p); - return p->value.second; - } - return result.first->value.second; -} - -template -template -typename std::conditional ::type& -aged_ordered_container :: -operator[] (Key&& key) -{ - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (key, - std::cref (m_config.key_compare()), d)); - if (result.second) - { - element* const p (new_element ( - std::piecewise_construct, - std::forward_as_tuple (std::move (key)), - std::forward_as_tuple ())); - m_cont.insert_commit (*p, d); - chronological.list.push_back (*p); - return p->value.second; - } - return result.first->value.second; -} - -//------------------------------------------------------------------------------ - -template -void -aged_ordered_container :: -clear() -{ - for (auto iter (chronological.list.begin()); - iter != chronological.list.end();) - delete_element (&*iter++); - chronological.list.clear(); - m_cont.clear(); -} - -// map, set -template -template -auto -aged_ordered_container :: -insert (value_type const& value) -> - typename std::enable_if >::type -{ - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (extract (value), - std::cref (m_config.key_compare()), d)); - if (result.second) - { - element* const p (new_element (value)); - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - return std::make_pair (iterator (result.first), false); -} - -// multimap, multiset -template -template -auto -aged_ordered_container :: -insert (value_type const& value) -> - typename std::enable_if ::type -{ - auto const before (m_cont.upper_bound ( - extract (value), std::cref (m_config.key_compare()))); - element* const p (new_element (value)); - chronological.list.push_back (*p); - auto const iter (m_cont.insert_before (before, *p)); - return iterator (iter); -} - -// set -template -template -auto -aged_ordered_container :: -insert (value_type&& value) -> - typename std::enable_if >::type -{ - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (extract (value), - std::cref (m_config.key_compare()), d)); - if (result.second) - { - element* const p (new_element (std::move (value))); - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - return std::make_pair (iterator (result.first), false); -} - -// multiset -template -template -auto -aged_ordered_container :: -insert (value_type&& value) -> - typename std::enable_if ::type -{ - auto const before (m_cont.upper_bound ( - extract (value), std::cref (m_config.key_compare()))); - element* const p (new_element (std::move (value))); - chronological.list.push_back (*p); - auto const iter (m_cont.insert_before (before, *p)); - return iterator (iter); -} - -//--- - -// map, set -template -template -auto -aged_ordered_container :: -insert (const_iterator hint, value_type const& value) -> - typename std::enable_if ::type -{ - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (hint.iterator(), - extract (value), std::cref (m_config.key_compare()), d)); - if (result.second) - { - element* const p (new_element (value)); - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return iterator (iter); - } - return iterator (result.first); -} - -// map, set -template -template -auto -aged_ordered_container :: -insert (const_iterator hint, value_type&& value) -> - typename std::enable_if ::type -{ - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (hint.iterator(), - extract (value), std::cref (m_config.key_compare()), d)); - if (result.second) - { - element* const p (new_element (std::move (value))); - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return iterator (iter); - } - return iterator (result.first); -} - -// map, set -template -template -auto -aged_ordered_container :: -emplace (Args&&... args) -> - typename std::enable_if >::type -{ - // VFALCO NOTE Its unfortunate that we need to - // construct element here - element* const p (new_element ( - std::forward (args)...)); - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (extract (p->value), - std::cref (m_config.key_compare()), d)); - if (result.second) - { - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - delete_element (p); - return std::make_pair (iterator (result.first), false); -} - -// multiset, multimap -template -template -auto -aged_ordered_container :: -emplace (Args&&... args) -> - typename std::enable_if ::type -{ - element* const p (new_element ( - std::forward (args)...)); - auto const before (m_cont.upper_bound (extract (p->value), - std::cref (m_config.key_compare()))); - chronological.list.push_back (*p); - auto const iter (m_cont.insert_before (before, *p)); - return iterator (iter); -} - -// map, set -template -template -auto -aged_ordered_container :: -emplace_hint (const_iterator hint, Args&&... args) -> - typename std::enable_if >::type -{ - // VFALCO NOTE Its unfortunate that we need to - // construct element here - element* const p (new_element ( - std::forward (args)...)); - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (hint.iterator(), - extract (p->value), std::cref (m_config.key_compare()), d)); - if (result.second) - { - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - delete_element (p); - return std::make_pair (iterator (result.first), false); -} - -template -template -detail::aged_container_iterator -aged_ordered_container :: -erase (detail::aged_container_iterator pos) -{ - unlink_and_delete_element(&*((pos++).iterator())); - return detail::aged_container_iterator < - false, Iterator, Base> (pos.iterator()); -} - -template -template -detail::aged_container_iterator -aged_ordered_container :: -erase (detail::aged_container_iterator first, - detail::aged_container_iterator last) -{ - for (; first != last;) - unlink_and_delete_element(&*((first++).iterator())); - - return detail::aged_container_iterator < - false, Iterator, Base> (first.iterator()); -} - -template -template -auto -aged_ordered_container :: -erase (K const& k) -> - size_type -{ - auto iter (m_cont.find (k, - std::cref (m_config.key_compare()))); - if (iter == m_cont.end()) - return 0; - size_type n (0); - for (;;) - { - auto p (&*iter++); - bool const done ( - m_config (*p, extract (iter->value))); - unlink_and_delete_element (p); - ++n; - if (done) - break; - } - return n; -} - -template -void -aged_ordered_container :: -swap (aged_ordered_container& other) noexcept -{ - swap_data (other); - std::swap (chronological, other.chronological); - std::swap (m_cont, other.m_cont); -} - -//------------------------------------------------------------------------------ - -template -template -auto -aged_ordered_container :: -touch (K const& k) -> - size_type -{ - auto const now (clock().now()); - size_type n (0); - auto const range (equal_range (k)); - for (auto iter : range) - { - touch (iter, now); - ++n; - } - return n; -} - -//------------------------------------------------------------------------------ - -template -template -bool -aged_ordered_container :: -operator== ( - aged_ordered_container const& other) const -{ - using Other = aged_ordered_container ; - if (size() != other.size()) - return false; - std::equal_to eq; - return std::equal (cbegin(), cend(), other.cbegin(), other.cend(), - [&eq, &other](value_type const& lhs, - typename Other::value_type const& rhs) - { - return eq (extract (lhs), other.extract (rhs)); - }); -} - -//------------------------------------------------------------------------------ - -template -template -void -aged_ordered_container :: -touch (detail::aged_container_iterator < - is_const, Iterator, Base> pos, - typename clock_type::time_point const& now) -{ - auto& e (*pos.iterator()); - e.when = now; - chronological.list.erase (chronological.list.iterator_to (e)); - chronological.list.push_back (e); -} - -template -template -typename std::enable_if ::type -aged_ordered_container :: -swap_data (aged_ordered_container& other) noexcept -{ - std::swap (m_config.key_compare(), other.m_config.key_compare()); - std::swap (m_config.alloc(), other.m_config.alloc()); - std::swap (m_config.clock, other.m_config.clock); -} - -template -template -typename std::enable_if ::type -aged_ordered_container :: -swap_data (aged_ordered_container& other) noexcept -{ - std::swap (m_config.key_compare(), other.m_config.key_compare()); - std::swap (m_config.clock, other.m_config.clock); -} - -} - -//------------------------------------------------------------------------------ - -template -struct is_aged_container > - : std::true_type -{ -}; - -// Free functions - -template -void swap ( - detail::aged_ordered_container & lhs, - detail::aged_ordered_container & rhs) noexcept -{ - lhs.swap (rhs); -} - -/** Expire aged container items past the specified age. */ -template -std::size_t expire (detail::aged_ordered_container < - IsMulti, IsMap, Key, T, Clock, Compare, Allocator>& c, - std::chrono::duration const& age) -{ - std::size_t n (0); - auto const expired (c.clock().now() - age); - for (auto iter (c.chronological.cbegin()); - iter != c.chronological.cend() && - iter.when() <= expired;) - { - iter = c.erase (iter); - ++n; - } - return n; -} - -} - -#endif diff --git a/beast/container/detail/aged_unordered_container.h b/beast/container/detail/aged_unordered_container.h deleted file mode 100644 index 52499f8b1c..0000000000 --- a/beast/container/detail/aged_unordered_container.h +++ /dev/null @@ -1,2554 +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_CONTAINER_DETAIL_AGED_UNORDERED_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_DETAIL_AGED_UNORDERED_CONTAINER_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* - -TODO - -- Add constructor variations that take a bucket count - -- Review for noexcept and exception guarantees - -- Call the safe version of is_permutation that takes 4 iterators - -*/ - -#ifndef BEAST_NO_CXX14_IS_PERMUTATION -#define BEAST_NO_CXX14_IS_PERMUTATION 1 -#endif - -namespace beast { -namespace detail { - -/** Associative container where each element is also indexed by time. - - This container mirrors the interface of the standard library unordered - associative containers, with the addition that each element is associated - with a `when` `time_point` which is obtained from the value of the clock's - `now`. The function `touch` updates the time for an element to the current - time as reported by the clock. - - An extra set of iterator types and member functions are provided in the - `chronological` memberspace that allow traversal in temporal or reverse - temporal order. This container is useful as a building block for caches - whose items expire after a certain amount of time. The chronological - iterators allow for fully customizable expiration strategies. - - @see aged_unordered_set, aged_unordered_multiset - @see aged_unordered_map, aged_unordered_multimap -*/ -template < - bool IsMulti, - bool IsMap, - class Key, - class T, - class Clock = std::chrono::steady_clock, - class Hash = std::hash , - class KeyEqual = std::equal_to , - class Allocator = std::allocator < - typename std::conditional , - Key>::type> -> -class aged_unordered_container -{ -public: - using clock_type = abstract_clock; - using time_point = typename clock_type::time_point; - using duration = typename clock_type::duration; - using key_type = Key; - using mapped_type = T; - using value_type = typename std::conditional , Key>::type; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - - // Introspection (for unit tests) - using is_unordered = std::true_type; - using is_multi = std::integral_constant ; - using is_map = std::integral_constant ; - -private: - static Key const& extract (value_type const& value) - { - return aged_associative_container_extract_t () (value); - } - - // VFALCO TODO hoist to remove template argument dependencies - struct element - : boost::intrusive::unordered_set_base_hook < - boost::intrusive::link_mode < - boost::intrusive::normal_link> - > - , boost::intrusive::list_base_hook < - boost::intrusive::link_mode < - boost::intrusive::normal_link> - > - { - // Stash types here so the iterator doesn't - // need to see the container declaration. - struct stashed - { - using value_type = typename aged_unordered_container::value_type; - using time_point = typename aged_unordered_container::time_point; - }; - - element ( - time_point const& when_, - value_type const& value_) - : value (value_) - , when (when_) - { - } - - element ( - time_point const& when_, - value_type&& value_) - : value (std::move (value_)) - , when (when_) - { - } - - template < - class... Args, - class = typename std::enable_if < - std::is_constructible ::value>::type - > - element (time_point const& when_, Args&&... args) - : value (std::forward (args)...) - , when (when_) - { - } - - value_type value; - time_point when; - }; - - // VFALCO TODO hoist to remove template argument dependencies - class ValueHash - : private empty_base_optimization - , public std::unary_function - { - public: - ValueHash () - { - } - - ValueHash (Hash const& hash) - : empty_base_optimization (hash) - { - } - - std::size_t operator() (element const& e) const - { - return this->member() (extract (e.value)); - } - - Hash& hash_function() - { - return this->member(); - } - - Hash const& hash_function() const - { - return this->member(); - } - }; - - // Compares value_type against element, used in find/insert_check - // VFALCO TODO hoist to remove template argument dependencies - class KeyValueEqual - : private empty_base_optimization - , public std::binary_function - { - public: - KeyValueEqual () - { - } - - KeyValueEqual (KeyEqual const& keyEqual) - : empty_base_optimization (keyEqual) - { - } - - // VFALCO NOTE WE might want only to enable these overloads - // if KeyEqual has is_transparent -#if 0 - template - bool operator() (K const& k, element const& e) const - { - return this->member() (k, extract (e.value)); - } - - template - bool operator() (element const& e, K const& k) const - { - return this->member() (extract (e.value), k); - } -#endif - - bool operator() (Key const& k, element const& e) const - { - return this->member() (k, extract (e.value)); - } - - bool operator() (element const& e, Key const& k) const - { - return this->member() (extract (e.value), k); - } - - bool operator() (element const& lhs, element const& rhs) const - { - return this->member() (extract (lhs.value), extract (rhs.value)); - } - - KeyEqual& key_eq() - { - return this->member(); - } - - KeyEqual const& key_eq() const - { - return this->member(); - } - }; - - using list_type = typename boost::intrusive::make_list >::type; - - using cont_type = typename std::conditional < - IsMulti, - typename boost::intrusive::make_unordered_multiset , - boost::intrusive::hash , - boost::intrusive::equal , - boost::intrusive::cache_begin - >::type, - typename boost::intrusive::make_unordered_set , - boost::intrusive::hash , - boost::intrusive::equal , - boost::intrusive::cache_begin - >::type - >::type; - - using bucket_type = typename cont_type::bucket_type; - using bucket_traits = typename cont_type::bucket_traits; - - using ElementAllocator = typename std::allocator_traits < - Allocator>::template rebind_alloc ; - - using ElementAllocatorTraits = std::allocator_traits ; - - using BucketAllocator = typename std::allocator_traits < - Allocator>::template rebind_alloc ; - - using BucketAllocatorTraits = std::allocator_traits ; - - class config_t - : private ValueHash - , private KeyValueEqual - , private empty_base_optimization - { - public: - explicit config_t ( - clock_type& clock_) - : clock (clock_) - { - } - - config_t ( - clock_type& clock_, - Hash const& hash) - : ValueHash (hash) - , clock (clock_) - { - } - - config_t ( - clock_type& clock_, - KeyEqual const& keyEqual) - : KeyValueEqual (keyEqual) - , clock (clock_) - { - } - - config_t ( - clock_type& clock_, - Allocator const& alloc_) - : empty_base_optimization (alloc_) - , clock (clock_) - { - } - - config_t ( - clock_type& clock_, - Hash const& hash, - KeyEqual const& keyEqual) - : ValueHash (hash) - , KeyValueEqual (keyEqual) - , clock (clock_) - { - } - - config_t ( - clock_type& clock_, - Hash const& hash, - Allocator const& alloc_) - : ValueHash (hash) - , empty_base_optimization (alloc_) - , clock (clock_) - { - } - - config_t ( - clock_type& clock_, - KeyEqual const& keyEqual, - Allocator const& alloc_) - : KeyValueEqual (keyEqual) - , empty_base_optimization (alloc_) - , clock (clock_) - { - } - - config_t ( - clock_type& clock_, - Hash const& hash, - KeyEqual const& keyEqual, - Allocator const& alloc_) - : ValueHash (hash) - , KeyValueEqual (keyEqual) - , empty_base_optimization (alloc_) - , clock (clock_) - { - } - - config_t (config_t const& other) - : ValueHash (other.hash_function()) - , KeyValueEqual (other.key_eq()) - , empty_base_optimization ( - ElementAllocatorTraits:: - select_on_container_copy_construction ( - other.alloc())) - , clock (other.clock) - { - } - - config_t (config_t const& other, Allocator const& alloc) - : ValueHash (other.hash_function()) - , KeyValueEqual (other.key_eq()) - , empty_base_optimization (alloc) - , clock (other.clock) - { - } - - config_t (config_t&& other) - : ValueHash (std::move (other.hash_function())) - , KeyValueEqual (std::move (other.key_eq())) - , empty_base_optimization ( - std::move (other.alloc())) - , clock (other.clock) - { - } - - config_t (config_t&& other, Allocator const& alloc) - : ValueHash (std::move (other.hash_function())) - , KeyValueEqual (std::move (other.key_eq())) - , empty_base_optimization (alloc) - , clock (other.clock) - { - } - - config_t& operator= (config_t const& other) - { - hash_function() = other.hash_function(); - key_eq() = other.key_eq(); - alloc() = other.alloc(); - clock = other.clock; - return *this; - } - - config_t& operator= (config_t&& other) - { - hash_function() = std::move (other.hash_function()); - key_eq() = std::move (other.key_eq()); - alloc() = std::move (other.alloc()); - clock = other.clock; - return *this; - } - - ValueHash& value_hash() - { - return *this; - } - - ValueHash const& value_hash() const - { - return *this; - } - - Hash& hash_function() - { - return ValueHash::hash_function(); - } - - Hash const& hash_function() const - { - return ValueHash::hash_function(); - } - - KeyValueEqual& key_value_equal() - { - return *this; - } - - KeyValueEqual const& key_value_equal() const - { - return *this; - } - - KeyEqual& key_eq() - { - return key_value_equal().key_eq(); - } - - KeyEqual const& key_eq() const - { - return key_value_equal().key_eq(); - } - - ElementAllocator& alloc() - { - return empty_base_optimization < - ElementAllocator>::member(); - } - - ElementAllocator const& alloc() const - { - return empty_base_optimization < - ElementAllocator>::member(); - } - - std::reference_wrapper clock; - }; - - class Buckets - { - public: - using vec_type = std::vector< - bucket_type, - typename std::allocator_traits :: - template rebind_alloc >; - - Buckets () - : m_max_load_factor (1.f) - , m_vec () - { - m_vec.resize ( - cont_type::suggested_upper_bucket_count (0)); - } - - Buckets (Allocator const& alloc) - : m_max_load_factor (1.f) - , m_vec (alloc) - { - m_vec.resize ( - cont_type::suggested_upper_bucket_count (0)); - } - - operator bucket_traits() - { - return bucket_traits (&m_vec[0], m_vec.size()); - } - - void clear() - { - m_vec.clear(); - } - - size_type max_bucket_count() const - { - return m_vec.max_size(); - } - - float& max_load_factor() - { - return m_max_load_factor; - } - - float const& max_load_factor() const - { - return m_max_load_factor; - } - - // count is the number of buckets - template - void rehash (size_type count, Container& c) - { - size_type const size (m_vec.size()); - if (count == size) - return; - if (count > m_vec.capacity()) - { - // Need two vectors otherwise we - // will destroy non-empty buckets. - vec_type vec (m_vec.get_allocator()); - std::swap (m_vec, vec); - m_vec.resize (count); - c.rehash (bucket_traits ( - &m_vec[0], m_vec.size())); - return; - } - // Rehash in place. - if (count > size) - { - // This should not reallocate since - // we checked capacity earlier. - m_vec.resize (count); - c.rehash (bucket_traits ( - &m_vec[0], count)); - return; - } - // Resize must happen after rehash otherwise - // we might destroy non-empty buckets. - c.rehash (bucket_traits ( - &m_vec[0], count)); - m_vec.resize (count); - } - - // Resize the buckets to accomodate at least n items. - template - void resize (size_type n, Container& c) - { - size_type const suggested ( - cont_type::suggested_upper_bucket_count (n)); - rehash (suggested, c); - } - - private: - float m_max_load_factor; - vec_type m_vec; - }; - - template - element* new_element (Args&&... args) - { - struct Deleter - { - std::reference_wrapper a_; - Deleter (ElementAllocator& a) - : a_(a) - { - } - - void - operator()(element* p) - { - ElementAllocatorTraits::deallocate (a_.get(), p, 1); - } - }; - - std::unique_ptr p (ElementAllocatorTraits::allocate ( - m_config.alloc(), 1), Deleter(m_config.alloc())); - ElementAllocatorTraits::construct (m_config.alloc(), - p.get(), clock().now(), std::forward (args)...); - return p.release(); - } - - void delete_element (element const* p) - { - ElementAllocatorTraits::destroy (m_config.alloc(), p); - ElementAllocatorTraits::deallocate ( - m_config.alloc(), const_cast(p), 1); - } - - void unlink_and_delete_element (element const* p) - { - chronological.list.erase ( - chronological.list.iterator_to (*p)); - m_cont.erase (m_cont.iterator_to (*p)); - delete_element (p); - } - -public: - using hasher = Hash; - using key_equal = KeyEqual; - using allocator_type = Allocator; - using reference = value_type&; - using const_reference = value_type const&; - using pointer = typename std::allocator_traits < - Allocator>::pointer; - using const_pointer = typename std::allocator_traits < - Allocator>::const_pointer; - - // A set iterator (IsMap==false) is always const - // because the elements of a set are immutable. - using iterator= detail::aged_container_iterator ; - using const_iterator = detail::aged_container_iterator ; - - using local_iterator = detail::aged_container_iterator ; - using const_local_iterator = detail::aged_container_iterator ; - - //-------------------------------------------------------------------------- - // - // Chronological ordered iterators - // - // "Memberspace" - // http://accu.org/index.php/journals/1527 - // - //-------------------------------------------------------------------------- - - class chronological_t - { - public: - // A set iterator (IsMap==false) is always const - // because the elements of a set are immutable. - using iterator = detail::aged_container_iterator < - ! IsMap, typename list_type::iterator>; - using const_iterator = detail::aged_container_iterator < - true, typename list_type::iterator>; - using reverse_iterator = detail::aged_container_iterator < - ! IsMap, typename list_type::reverse_iterator>; - using const_reverse_iterator = detail::aged_container_iterator < - true, typename list_type::reverse_iterator>; - - iterator begin () - { - return iterator (list.begin()); - } - - const_iterator begin () const - { - return const_iterator (list.begin ()); - } - - const_iterator cbegin() const - { - return const_iterator (list.begin ()); - } - - iterator end () - { - return iterator (list.end ()); - } - - const_iterator end () const - { - return const_iterator (list.end ()); - } - - const_iterator cend () const - { - return const_iterator (list.end ()); - } - - reverse_iterator rbegin () - { - return reverse_iterator (list.rbegin()); - } - - const_reverse_iterator rbegin () const - { - return const_reverse_iterator (list.rbegin ()); - } - - const_reverse_iterator crbegin() const - { - return const_reverse_iterator (list.rbegin ()); - } - - reverse_iterator rend () - { - return reverse_iterator (list.rend ()); - } - - const_reverse_iterator rend () const - { - return const_reverse_iterator (list.rend ()); - } - - const_reverse_iterator crend () const - { - return const_reverse_iterator (list.rend ()); - } - - iterator iterator_to (value_type& value) - { - static_assert (std::is_standard_layout ::value, - "must be standard layout"); - return list.iterator_to (*reinterpret_cast ( - reinterpret_cast(&value)-((std::size_t) - std::addressof(((element*)0)->member)))); - } - - const_iterator iterator_to (value_type const& value) const - { - static_assert (std::is_standard_layout ::value, - "must be standard layout"); - return list.iterator_to (*reinterpret_cast ( - reinterpret_cast(&value)-((std::size_t) - std::addressof(((element*)0)->member)))); - } - - private: - chronological_t () - { - } - - chronological_t (chronological_t const&) = delete; - chronological_t (chronological_t&&) = delete; - - friend class aged_unordered_container; - list_type mutable list; - } chronological; - - //-------------------------------------------------------------------------- - // - // Construction - // - //-------------------------------------------------------------------------- - - aged_unordered_container() = delete; - - explicit aged_unordered_container (clock_type& clock); - - aged_unordered_container (clock_type& clock, Hash const& hash); - - aged_unordered_container (clock_type& clock, - KeyEqual const& key_eq); - - aged_unordered_container (clock_type& clock, - Allocator const& alloc); - - aged_unordered_container (clock_type& clock, - Hash const& hash, KeyEqual const& key_eq); - - aged_unordered_container (clock_type& clock, - Hash const& hash, Allocator const& alloc); - - aged_unordered_container (clock_type& clock, - KeyEqual const& key_eq, Allocator const& alloc); - - aged_unordered_container ( - clock_type& clock, Hash const& hash, KeyEqual const& key_eq, - Allocator const& alloc); - - template - aged_unordered_container (InputIt first, InputIt last, - clock_type& clock); - - template - aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, Hash const& hash); - - template - aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, KeyEqual const& key_eq); - - template - aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, Allocator const& alloc); - - template - aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, Hash const& hash, KeyEqual const& key_eq); - - template - aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, Hash const& hash, Allocator const& alloc); - - template - aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, KeyEqual const& key_eq, - Allocator const& alloc); - - template - aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, Hash const& hash, KeyEqual const& key_eq, - Allocator const& alloc); - - aged_unordered_container (aged_unordered_container const& other); - - aged_unordered_container (aged_unordered_container const& other, - Allocator const& alloc); - - aged_unordered_container (aged_unordered_container&& other); - - aged_unordered_container (aged_unordered_container&& other, - Allocator const& alloc); - - aged_unordered_container (std::initializer_list init, - clock_type& clock); - - aged_unordered_container (std::initializer_list init, - clock_type& clock, Hash const& hash); - - aged_unordered_container (std::initializer_list init, - clock_type& clock, KeyEqual const& key_eq); - - aged_unordered_container (std::initializer_list init, - clock_type& clock, Allocator const& alloc); - - aged_unordered_container (std::initializer_list init, - clock_type& clock, Hash const& hash, KeyEqual const& key_eq); - - aged_unordered_container (std::initializer_list init, - clock_type& clock, Hash const& hash, Allocator const& alloc); - - aged_unordered_container (std::initializer_list init, - clock_type& clock, KeyEqual const& key_eq, Allocator const& alloc); - - aged_unordered_container (std::initializer_list init, - clock_type& clock, Hash const& hash, KeyEqual const& key_eq, - Allocator const& alloc); - - ~aged_unordered_container(); - - aged_unordered_container& operator= (aged_unordered_container const& other); - - aged_unordered_container& operator= (aged_unordered_container&& other); - - aged_unordered_container& operator= (std::initializer_list init); - - allocator_type get_allocator() const - { - return m_config.alloc(); - } - - clock_type& clock() - { - return m_config.clock; - } - - clock_type const& clock() const - { - return m_config.clock; - } - - //-------------------------------------------------------------------------- - // - // Element access (maps) - // - //-------------------------------------------------------------------------- - - template < - class K, - bool maybe_multi = IsMulti, - bool maybe_map = IsMap, - class = typename std::enable_if ::type> - typename std::conditional ::type& - at (K const& k); - - template < - class K, - bool maybe_multi = IsMulti, - bool maybe_map = IsMap, - class = typename std::enable_if ::type> - typename std::conditional ::type const& - at (K const& k) const; - - template < - bool maybe_multi = IsMulti, - bool maybe_map = IsMap, - class = typename std::enable_if ::type> - typename std::conditional ::type& - operator[] (Key const& key); - - template < - bool maybe_multi = IsMulti, - bool maybe_map = IsMap, - class = typename std::enable_if ::type> - typename std::conditional ::type& - operator[] (Key&& key); - - //-------------------------------------------------------------------------- - // - // Iterators - // - //-------------------------------------------------------------------------- - - iterator - begin () - { - return iterator (m_cont.begin()); - } - - const_iterator - begin () const - { - return const_iterator (m_cont.begin ()); - } - - const_iterator - cbegin() const - { - return const_iterator (m_cont.begin ()); - } - - iterator - end () - { - return iterator (m_cont.end ()); - } - - const_iterator - end () const - { - return const_iterator (m_cont.end ()); - } - - const_iterator - cend () const - { - return const_iterator (m_cont.end ()); - } - - iterator - iterator_to (value_type& value) - { - static_assert (std::is_standard_layout ::value, - "must be standard layout"); - return m_cont.iterator_to (*reinterpret_cast ( - reinterpret_cast(&value)-((std::size_t) - std::addressof(((element*)0)->member)))); - } - - const_iterator - iterator_to (value_type const& value) const - { - static_assert (std::is_standard_layout ::value, - "must be standard layout"); - return m_cont.iterator_to (*reinterpret_cast ( - reinterpret_cast(&value)-((std::size_t) - std::addressof(((element*)0)->member)))); - } - - //-------------------------------------------------------------------------- - // - // Capacity - // - //-------------------------------------------------------------------------- - - bool empty() const noexcept - { - return m_cont.empty(); - } - - size_type size() const noexcept - { - return m_cont.size(); - } - - size_type max_size() const noexcept - { - return m_config.max_size(); - } - - //-------------------------------------------------------------------------- - // - // Modifiers - // - //-------------------------------------------------------------------------- - - void clear(); - - // map, set - template - auto - insert (value_type const& value) -> - typename std::enable_if >::type; - - // multimap, multiset - template - auto - insert (value_type const& value) -> - typename std::enable_if ::type; - - // map, set - template - auto - insert (value_type&& value) -> - typename std::enable_if >::type; - - // multimap, multiset - template - auto - insert (value_type&& value) -> - typename std::enable_if ::type; - - // map, set - template - typename std::enable_if ::type - insert (const_iterator /*hint*/, value_type const& value) - { - // Hint is ignored but we provide the interface so - // callers may use ordered and unordered interchangeably. - return insert (value).first; - } - - // multimap, multiset - template - typename std::enable_if ::type - insert (const_iterator /*hint*/, value_type const& value) - { - // VFALCO TODO The hint could be used to let - // the client order equal ranges - return insert (value); - } - - // map, set - template - typename std::enable_if ::type - insert (const_iterator /*hint*/, value_type&& value) - { - // Hint is ignored but we provide the interface so - // callers may use ordered and unordered interchangeably. - return insert (std::move (value)).first; - } - - // multimap, multiset - template - typename std::enable_if ::type - insert (const_iterator /*hint*/, value_type&& value) - { - // VFALCO TODO The hint could be used to let - // the client order equal ranges - return insert (std::move (value)); - } - - // map, multimap - template < - class P, - bool maybe_map = IsMap - > - typename std::enable_if ::value, - typename std::conditional - >::type - >::type - insert (P&& value) - { - return emplace (std::forward

(value)); - } - - // map, multimap - template < - class P, - bool maybe_map = IsMap - > - typename std::enable_if ::value, - typename std::conditional - >::type - >::type - insert (const_iterator hint, P&& value) - { - return emplace_hint (hint, std::forward

(value)); - } - - template - void insert (InputIt first, InputIt last) - { - insert (first, last, - typename std::iterator_traits < - InputIt>::iterator_category()); - } - - void - insert (std::initializer_list init) - { - insert (init.begin(), init.end()); - } - - // set, map - template - auto - emplace (Args&&... args) -> - typename std::enable_if >::type; - - // multiset, multimap - template - auto - emplace (Args&&... args) -> - typename std::enable_if ::type; - - // set, map - template - auto - emplace_hint (const_iterator /*hint*/, Args&&... args) -> - typename std::enable_if >::type; - - // multiset, multimap - template - typename std::enable_if ::type - emplace_hint (const_iterator /*hint*/, Args&&... args) - { - // VFALCO TODO The hint could be used for multi, to let - // the client order equal ranges - return emplace ( - std::forward (args)...); - } - - template - detail::aged_container_iterator - erase (detail::aged_container_iterator < - is_const, Iterator, Base> pos); - - template - detail::aged_container_iterator - erase (detail::aged_container_iterator < - is_const, Iterator, Base> first, - detail::aged_container_iterator < - is_const, Iterator, Base> last); - - template - auto - erase (K const& k) -> - size_type; - - void - swap (aged_unordered_container& other) noexcept; - - template - void - touch (detail::aged_container_iterator < - is_const, Iterator, Base> pos) - { - touch (pos, clock().now()); - } - - template - auto - touch (K const& k) -> - size_type; - - //-------------------------------------------------------------------------- - // - // Lookup - // - //-------------------------------------------------------------------------- - - // VFALCO TODO Respect is_transparent (c++14) - template - size_type - count (K const& k) const - { - return m_cont.count (k, std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal())); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - iterator - find (K const& k) - { - return iterator (m_cont.find (k, - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()))); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - const_iterator - find (K const& k) const - { - return const_iterator (m_cont.find (k, - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()))); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - std::pair - equal_range (K const& k) - { - auto const r (m_cont.equal_range (k, - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()))); - return std::make_pair (iterator (r.first), - iterator (r.second)); - } - - // VFALCO TODO Respect is_transparent (c++14) - template - std::pair - equal_range (K const& k) const - { - auto const r (m_cont.equal_range (k, - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()))); - return std::make_pair (const_iterator (r.first), - const_iterator (r.second)); - } - - //-------------------------------------------------------------------------- - // - // Bucket interface - // - //-------------------------------------------------------------------------- - - local_iterator begin (size_type n) - { - return local_iterator (m_cont.begin (n)); - } - - const_local_iterator begin (size_type n) const - { - return const_local_iterator (m_cont.begin (n)); - } - - const_local_iterator cbegin (size_type n) const - { - return const_local_iterator (m_cont.begin (n)); - } - - local_iterator end (size_type n) - { - return local_iterator (m_cont.end (n)); - } - - const_local_iterator end (size_type n) const - { - return const_local_iterator (m_cont.end (n)); - } - - const_local_iterator cend (size_type n) const - { - return const_local_iterator (m_cont.end (n)); - } - - size_type bucket_count() const - { - return m_cont.bucket_count(); - } - - size_type max_bucket_count() const - { - return m_buck.max_bucket_count(); - } - - size_type bucket_size (size_type n) const - { - return m_cont.bucket_size (n); - } - - size_type bucket (Key const& k) const - { - assert (bucket_count() != 0); - return m_cont.bucket (k, - std::cref (m_config.hash_function())); - } - - //-------------------------------------------------------------------------- - // - // Hash policy - // - //-------------------------------------------------------------------------- - - float load_factor() const - { - return size() / - static_cast (m_cont.bucket_count()); - } - - float max_load_factor() const - { - return m_buck.max_load_factor(); - } - - void max_load_factor (float ml) - { - m_buck.max_load_factor () = - std::max (ml, m_buck.max_load_factor()); - } - - void rehash (size_type count) - { - count = std::max (count, - size_type (size() / max_load_factor())); - m_buck.rehash (count, m_cont); - } - - void reserve (size_type count) - { - rehash (std::ceil (count / max_load_factor())); - } - - //-------------------------------------------------------------------------- - // - // Observers - // - //-------------------------------------------------------------------------- - - hasher const& hash_function() const - { - return m_config.hash_function(); - } - - key_equal const& key_eq () const - { - return m_config.key_eq(); - } - - //-------------------------------------------------------------------------- - // - // Comparison - // - //-------------------------------------------------------------------------- - - // This differs from the standard in that the comparison - // is only done on the key portion of the value type, ignoring - // the mapped type. - // - template < - bool OtherIsMap, - class OtherKey, - class OtherT, - class OtherDuration, - class OtherHash, - class OtherAllocator, - bool maybe_multi = IsMulti - > - typename std::enable_if ::type - operator== ( - aged_unordered_container const& other) const; - - template < - bool OtherIsMap, - class OtherKey, - class OtherT, - class OtherDuration, - class OtherHash, - class OtherAllocator, - bool maybe_multi = IsMulti - > - typename std::enable_if ::type - operator== ( - aged_unordered_container const& other) const; - - template < - bool OtherIsMulti, - bool OtherIsMap, - class OtherKey, - class OtherT, - class OtherDuration, - class OtherHash, - class OtherAllocator - > - bool operator!= ( - aged_unordered_container const& other) const - { - return ! (this->operator== (other)); - } - -private: - bool - would_exceed (size_type additional) const - { - return size() + additional > - bucket_count() * max_load_factor(); - } - - void - maybe_rehash (size_type additional) - { - if (would_exceed (additional)) - m_buck.resize (size() + additional, m_cont); - assert (load_factor() <= max_load_factor()); - } - - // map, set - template - auto - insert_unchecked (value_type const& value) -> - typename std::enable_if >::type; - - // multimap, multiset - template - auto - insert_unchecked (value_type const& value) -> - typename std::enable_if ::type; - - template - void - insert_unchecked (InputIt first, InputIt last) - { - for (; first != last; ++first) - insert_unchecked (*first); - } - - template - void - insert (InputIt first, InputIt last, - std::input_iterator_tag) - { - for (; first != last; ++first) - insert (*first); - } - - template - void - insert (InputIt first, InputIt last, - std::random_access_iterator_tag) - { - auto const n (std::distance (first, last)); - maybe_rehash (n); - insert_unchecked (first, last); - } - - template - void - touch (detail::aged_container_iterator < - is_const, Iterator, Base> pos, - typename clock_type::time_point const& now) - { - auto& e (*pos.iterator()); - e.when = now; - chronological.list.erase (chronological.list.iterator_to (e)); - chronological.list.push_back (e); - } - - template ::propagate_on_container_swap::value> - typename std::enable_if ::type - swap_data (aged_unordered_container& other) noexcept - { - std::swap (m_config.key_compare(), other.m_config.key_compare()); - std::swap (m_config.alloc(), other.m_config.alloc()); - std::swap (m_config.clock, other.m_config.clock); - } - - template ::propagate_on_container_swap::value> - typename std::enable_if ::type - swap_data (aged_unordered_container& other) noexcept - { - std::swap (m_config.key_compare(), other.m_config.key_compare()); - std::swap (m_config.clock, other.m_config.clock); - } - -private: - config_t m_config; - Buckets m_buck; - cont_type mutable m_cont; -}; - -//------------------------------------------------------------------------------ - -template -aged_unordered_container :: -aged_unordered_container ( - clock_type& clock) - : m_config (clock) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ -} - -template -aged_unordered_container :: -aged_unordered_container ( - clock_type& clock, - Hash const& hash) - : m_config (clock, hash) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ -} - -template -aged_unordered_container :: -aged_unordered_container ( - clock_type& clock, - KeyEqual const& key_eq) - : m_config (clock, key_eq) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ -} - -template -aged_unordered_container :: -aged_unordered_container ( - clock_type& clock, - Allocator const& alloc) - : m_config (clock, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ -} - -template -aged_unordered_container :: -aged_unordered_container ( - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) - : m_config (clock, hash, key_eq) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ -} - -template -aged_unordered_container :: -aged_unordered_container ( - clock_type& clock, - Hash const& hash, - Allocator const& alloc) - : m_config (clock, hash, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ -} - -template -aged_unordered_container :: -aged_unordered_container ( - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) - : m_config (clock, key_eq, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ -} - -template -aged_unordered_container :: -aged_unordered_container ( - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) - : m_config (clock, hash, key_eq, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ -} - -template -template -aged_unordered_container :: -aged_unordered_container (InputIt first, InputIt last, - clock_type& clock) - : m_config (clock) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (first, last); -} - -template -template -aged_unordered_container :: -aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, - Hash const& hash) - : m_config (clock, hash) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (first, last); -} - -template -template -aged_unordered_container :: -aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, - KeyEqual const& key_eq) - : m_config (clock, key_eq) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (first, last); -} - -template -template -aged_unordered_container :: -aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, - Allocator const& alloc) - : m_config (clock, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (first, last); -} - -template -template -aged_unordered_container :: -aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) - : m_config (clock, hash, key_eq) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (first, last); -} - -template -template -aged_unordered_container :: -aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, - Hash const& hash, - Allocator const& alloc) - : m_config (clock, hash, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (first, last); -} - -template -template -aged_unordered_container :: -aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) - : m_config (clock, key_eq, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (first, last); -} - -template -template -aged_unordered_container :: -aged_unordered_container (InputIt first, InputIt last, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) - : m_config (clock, hash, key_eq, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (first, last); -} - -template -aged_unordered_container :: -aged_unordered_container (aged_unordered_container const& other) - : m_config (other.m_config) - , m_buck (m_config.alloc()) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (other.cbegin(), other.cend()); -} - -template -aged_unordered_container :: -aged_unordered_container (aged_unordered_container const& other, - Allocator const& alloc) - : m_config (other.m_config, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (other.cbegin(), other.cend()); -} - -template -aged_unordered_container :: -aged_unordered_container (aged_unordered_container&& other) - : m_config (std::move (other.m_config)) - , m_buck (std::move (other.m_buck)) - , m_cont (std::move (other.m_cont)) -{ - chronological.list = std::move (other.chronological.list); -} - -template -aged_unordered_container :: -aged_unordered_container (aged_unordered_container&& other, - Allocator const& alloc) - : m_config (std::move (other.m_config), alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (other.cbegin(), other.cend()); - other.clear (); -} - -template -aged_unordered_container :: -aged_unordered_container (std::initializer_list init, - clock_type& clock) - : m_config (clock) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (init.begin(), init.end()); -} - -template -aged_unordered_container :: -aged_unordered_container (std::initializer_list init, - clock_type& clock, - Hash const& hash) - : m_config (clock, hash) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (init.begin(), init.end()); -} - -template -aged_unordered_container :: -aged_unordered_container (std::initializer_list init, - clock_type& clock, - KeyEqual const& key_eq) - : m_config (clock, key_eq) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (init.begin(), init.end()); -} - -template -aged_unordered_container :: -aged_unordered_container (std::initializer_list init, - clock_type& clock, - Allocator const& alloc) - : m_config (clock, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (init.begin(), init.end()); -} - -template -aged_unordered_container :: -aged_unordered_container (std::initializer_list init, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq) - : m_config (clock, hash, key_eq) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (init.begin(), init.end()); -} - -template -aged_unordered_container :: -aged_unordered_container (std::initializer_list init, - clock_type& clock, - Hash const& hash, - Allocator const& alloc) - : m_config (clock, hash, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (init.begin(), init.end()); -} - -template -aged_unordered_container :: -aged_unordered_container (std::initializer_list init, - clock_type& clock, - KeyEqual const& key_eq, - Allocator const& alloc) - : m_config (clock, key_eq, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (init.begin(), init.end()); -} - -template -aged_unordered_container :: -aged_unordered_container (std::initializer_list init, - clock_type& clock, - Hash const& hash, - KeyEqual const& key_eq, - Allocator const& alloc) - : m_config (clock, hash, key_eq, alloc) - , m_buck (alloc) - , m_cont (m_buck, - std::cref (m_config.value_hash()), - std::cref (m_config.key_value_equal())) -{ - insert (init.begin(), init.end()); -} - -template -aged_unordered_container :: -~aged_unordered_container() -{ - clear(); -} - -template -auto -aged_unordered_container :: -operator= (aged_unordered_container const& other) - -> aged_unordered_container& -{ - if (this != &other) - { - size_type const n (other.size()); - clear(); - m_config = other.m_config; - m_buck = Buckets (m_config.alloc()); - maybe_rehash (n); - insert_unchecked (other.begin(), other.end()); - } - return *this; -} - -template -auto -aged_unordered_container :: -operator= (aged_unordered_container&& other) -> - aged_unordered_container& -{ - size_type const n (other.size()); - clear(); - m_config = std::move (other.m_config); - m_buck = Buckets (m_config.alloc()); - maybe_rehash (n); - insert_unchecked (other.begin(), other.end()); - other.clear(); - return *this; -} - -template -auto -aged_unordered_container :: -operator= (std::initializer_list init) -> - aged_unordered_container& -{ - clear (); - insert (init); - return *this; -} - -//------------------------------------------------------------------------------ - -template -template -typename std::conditional ::type& -aged_unordered_container :: -at (K const& k) -{ - auto const iter (m_cont.find (k, - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()))); - if (iter == m_cont.end()) - throw std::out_of_range ("key not found"); - return iter->value.second; -} - -template -template -typename std::conditional ::type const& -aged_unordered_container :: -at (K const& k) const -{ - auto const iter (m_cont.find (k, - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()))); - if (iter == m_cont.end()) - throw std::out_of_range ("key not found"); - return iter->value.second; -} - -template -template -typename std::conditional ::type& -aged_unordered_container :: -operator[] (Key const& key) -{ - maybe_rehash (1); - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (key, - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()), d)); - if (result.second) - { - element* const p (new_element ( - std::piecewise_construct, - std::forward_as_tuple (key), - std::forward_as_tuple ())); - m_cont.insert_commit (*p, d); - chronological.list.push_back (*p); - return p->value.second; - } - return result.first->value.second; -} - -template -template -typename std::conditional ::type& -aged_unordered_container :: -operator[] (Key&& key) -{ - maybe_rehash (1); - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (key, - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()), d)); - if (result.second) - { - element* const p (new_element ( - std::piecewise_construct, - std::forward_as_tuple (std::move (key)), - std::forward_as_tuple ())); - m_cont.insert_commit (*p, d); - chronological.list.push_back (*p); - return p->value.second; - } - return result.first->value.second; -} - -//------------------------------------------------------------------------------ - -template -void -aged_unordered_container :: -clear() -{ - for (auto iter (chronological.list.begin()); - iter != chronological.list.end();) - unlink_and_delete_element (&*iter++); - chronological.list.clear(); - m_cont.clear(); - m_buck.clear(); -} - -// map, set -template -template -auto -aged_unordered_container :: -insert (value_type const& value) -> - typename std::enable_if >::type -{ - maybe_rehash (1); - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (extract (value), - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()), d)); - if (result.second) - { - element* const p (new_element (value)); - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - return std::make_pair (iterator (result.first), false); -} - -// multimap, multiset -template -template -auto -aged_unordered_container :: -insert (value_type const& value) -> - typename std::enable_if ::type -{ - maybe_rehash (1); - element* const p (new_element (value)); - chronological.list.push_back (*p); - auto const iter (m_cont.insert (*p)); - return iterator (iter); -} - -// map, set -template -template -auto -aged_unordered_container :: -insert (value_type&& value) -> - typename std::enable_if >::type -{ - maybe_rehash (1); - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (extract (value), - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()), d)); - if (result.second) - { - element* const p (new_element (std::move (value))); - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - return std::make_pair (iterator (result.first), false); -} - -// multimap, multiset -template -template -auto -aged_unordered_container :: -insert (value_type&& value) -> - typename std::enable_if ::type -{ - maybe_rehash (1); - element* const p (new_element (std::move (value))); - chronological.list.push_back (*p); - auto const iter (m_cont.insert (*p)); - return iterator (iter); -} - -#if 1 // Use insert() instead of insert_check() insert_commit() -// set, map -template -template -auto -aged_unordered_container :: -emplace (Args&&... args) -> - typename std::enable_if >::type -{ - maybe_rehash (1); - // VFALCO NOTE Its unfortunate that we need to - // construct element here - element* const p (new_element (std::forward (args)...)); - auto const result (m_cont.insert (*p)); - if (result.second) - { - chronological.list.push_back (*p); - return std::make_pair (iterator (result.first), true); - } - delete_element (p); - return std::make_pair (iterator (result.first), false); -} -#else // As original, use insert_check() / insert_commit () pair. -// set, map -template -template -auto -aged_unordered_container :: -emplace (Args&&... args) -> - typename std::enable_if >::type -{ - maybe_rehash (1); - // VFALCO NOTE Its unfortunate that we need to - // construct element here - element* const p (new_element ( - std::forward (args)...)); - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (extract (p->value), - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()), d)); - if (result.second) - { - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - delete_element (p); - return std::make_pair (iterator (result.first), false); -} -#endif // 0 - -// multiset, multimap -template -template -auto -aged_unordered_container :: -emplace (Args&&... args) -> - typename std::enable_if ::type -{ - maybe_rehash (1); - element* const p (new_element ( - std::forward (args)...)); - chronological.list.push_back (*p); - auto const iter (m_cont.insert (*p)); - return iterator (iter); -} - -// set, map -template -template -auto -aged_unordered_container :: -emplace_hint (const_iterator /*hint*/, Args&&... args) -> - typename std::enable_if >::type -{ - maybe_rehash (1); - // VFALCO NOTE Its unfortunate that we need to - // construct element here - element* const p (new_element ( - std::forward (args)...)); - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (extract (p->value), - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()), d)); - if (result.second) - { - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - delete_element (p); - return std::make_pair (iterator (result.first), false); -} - -template -template -detail::aged_container_iterator -aged_unordered_container :: -erase (detail::aged_container_iterator < - is_const, Iterator, Base> pos) -{ - unlink_and_delete_element(&*((pos++).iterator())); - return detail::aged_container_iterator < - false, Iterator, Base> (pos.iterator()); -} - -template -template -detail::aged_container_iterator -aged_unordered_container :: -erase (detail::aged_container_iterator < - is_const, Iterator, Base> first, - detail::aged_container_iterator < - is_const, Iterator, Base> last) -{ - for (; first != last;) - unlink_and_delete_element(&*((first++).iterator())); - - return detail::aged_container_iterator < - false, Iterator, Base> (first.iterator()); -} - -template -template -auto -aged_unordered_container :: -erase (K const& k) -> - size_type -{ - auto iter (m_cont.find (k, std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()))); - if (iter == m_cont.end()) - return 0; - size_type n (0); - for (;;) - { - auto p (&*iter++); - bool const done ( - m_config (*p, extract (iter->value))); - unlink_and_delete_element (p); - ++n; - if (done) - break; - } - return n; -} - -template -void -aged_unordered_container :: -swap (aged_unordered_container& other) noexcept -{ - swap_data (other); - std::swap (chronological, other.chronological); - std::swap (m_cont, other.m_cont); -} - -template -template -auto -aged_unordered_container :: -touch (K const& k) -> - size_type -{ - auto const now (clock().now()); - size_type n (0); - auto const range (equal_range (k)); - for (auto iter : range) - { - touch (iter, now); - ++n; - } - return n; -} - -template -template < - bool OtherIsMap, - class OtherKey, - class OtherT, - class OtherDuration, - class OtherHash, - class OtherAllocator, - bool maybe_multi -> -typename std::enable_if ::type -aged_unordered_container < - IsMulti, IsMap, Key, T, Clock, Hash, KeyEqual, Allocator>:: -operator== ( - aged_unordered_container const& other) const -{ - if (size() != other.size()) - return false; - for (auto iter (cbegin()), last (cend()), olast (other.cend()); - iter != last; ++iter) - { - auto oiter (other.find (extract (*iter))); - if (oiter == olast) - return false; - } - return true; -} - -template -template < - bool OtherIsMap, - class OtherKey, - class OtherT, - class OtherDuration, - class OtherHash, - class OtherAllocator, - bool maybe_multi -> -typename std::enable_if ::type -aged_unordered_container < - IsMulti, IsMap, Key, T, Clock, Hash, KeyEqual, Allocator>:: -operator== ( - aged_unordered_container const& other) const -{ - if (size() != other.size()) - return false; - using EqRng = std::pair ; - for (auto iter (cbegin()), last (cend()); iter != last;) - { - auto const& k (extract (*iter)); - auto const eq (equal_range (k)); - auto const oeq (other.equal_range (k)); -#if BEAST_NO_CXX14_IS_PERMUTATION - if (std::distance (eq.first, eq.second) != - std::distance (oeq.first, oeq.second) || - ! std::is_permutation (eq.first, eq.second, oeq.first)) - return false; -#else - if (! std::is_permutation (eq.first, - eq.second, oeq.first, oeq.second)) - return false; -#endif - iter = eq.second; - } - return true; -} - -//------------------------------------------------------------------------------ - -// map, set -template -template -auto -aged_unordered_container :: -insert_unchecked (value_type const& value) -> - typename std::enable_if >::type -{ - typename cont_type::insert_commit_data d; - auto const result (m_cont.insert_check (extract (value), - std::cref (m_config.hash_function()), - std::cref (m_config.key_value_equal()), d)); - if (result.second) - { - element* const p (new_element (value)); - auto const iter (m_cont.insert_commit (*p, d)); - chronological.list.push_back (*p); - return std::make_pair (iterator (iter), true); - } - return std::make_pair (iterator (result.first), false); -} - -// multimap, multiset -template -template -auto -aged_unordered_container :: -insert_unchecked (value_type const& value) -> - typename std::enable_if ::type -{ - element* const p (new_element (value)); - chronological.list.push_back (*p); - auto const iter (m_cont.insert (*p)); - return iterator (iter); -} - -//------------------------------------------------------------------------------ - -} - -//------------------------------------------------------------------------------ - -template -struct is_aged_container > - : std::true_type -{ -}; - -// Free functions - -template -void swap ( - detail::aged_unordered_container & lhs, - detail::aged_unordered_container & rhs) noexcept -{ - lhs.swap (rhs); -} - -/** Expire aged container items past the specified age. */ -template -std::size_t expire (detail::aged_unordered_container < - IsMulti, IsMap, Key, T, Clock, Hash, KeyEqual, Allocator>& c, - std::chrono::duration const& age) noexcept -{ - std::size_t n (0); - auto const expired (c.clock().now() - age); - for (auto iter (c.chronological.cbegin()); - iter != c.chronological.cend() && - iter.when() <= expired;) - { - iter = c.erase (iter); - ++n; - } - return n; -} - -} - -#endif diff --git a/beast/container/tests/aged_associative_container.test.cpp b/beast/container/tests/aged_associative_container.test.cpp deleted file mode 100644 index 1b66f3b356..0000000000 --- a/beast/container/tests/aged_associative_container.test.cpp +++ /dev/null @@ -1,2011 +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 -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#ifndef BEAST_AGED_UNORDERED_NO_ALLOC_DEFAULTCTOR -# ifdef _MSC_VER -# define BEAST_AGED_UNORDERED_NO_ALLOC_DEFAULTCTOR 0 -# else -# define BEAST_AGED_UNORDERED_NO_ALLOC_DEFAULTCTOR 1 -# endif -#endif - -#ifndef BEAST_CONTAINER_EXTRACT_NOREF -# ifdef _MSC_VER -# define BEAST_CONTAINER_EXTRACT_NOREF 1 -# else -# define BEAST_CONTAINER_EXTRACT_NOREF 1 -# endif -#endif - -namespace beast { - -class aged_associative_container_test_base : public unit_test::suite -{ -public: - template - struct CompT - { - explicit CompT (int) - { - } - - CompT (CompT const&) - { - } - - bool operator() (T const& lhs, T const& rhs) const - { - return m_less (lhs, rhs); - } - - private: - CompT () = delete; - std::less m_less; - }; - - template - class HashT - { - public: - explicit HashT (int) - { - } - - std::size_t operator() (T const& t) const - { - return m_hash (t); - } - - private: - HashT() = delete; - std::hash m_hash; - }; - - template - struct EqualT - { - public: - explicit EqualT (int) - { - } - - bool operator() (T const& lhs, T const& rhs) const - { - return m_eq (lhs, rhs); - } - - private: - EqualT() = delete; - std::equal_to m_eq; - }; - - template - struct AllocT - { - using value_type = T; - - //using std::true_type::type = propagate_on_container_swap :; - - template - struct rebind - { - using other = AllocT ; - }; - - explicit AllocT (int) - { - } - - AllocT (AllocT const&) - { - } - - template - AllocT (AllocT const&) - { - } - - template - bool operator== (AllocT const&) const - { - return true; - } - - T* allocate (std::size_t n, T const* = 0) - { - return static_cast ( - ::operator new (n * sizeof(T))); - } - - void deallocate (T* p, std::size_t) - { - ::operator delete (p); - } - -#if ! BEAST_AGED_UNORDERED_NO_ALLOC_DEFAULTCTOR - AllocT () - { - } -#else - private: - AllocT() = delete; -#endif - }; - - //-------------------------------------------------------------------------- - - // ordered - template - class MaybeUnordered : public Base - { - public: - using Comp = std::less ; - using MyComp = CompT ; - - protected: - static std::string name_ordered_part() - { - return ""; - } - }; - - // unordered - template - class MaybeUnordered : public Base - { - public: - using Hash = std::hash ; - using Equal = std::equal_to ; - using MyHash = HashT ; - using MyEqual = EqualT ; - - protected: - static std::string name_ordered_part() - { - return "unordered_"; - } - }; - - // unique - template - class MaybeMulti : public Base - { - public: - protected: - static std::string name_multi_part() - { - return ""; - } - }; - - // multi - template - class MaybeMulti : public Base - { - public: - protected: - static std::string name_multi_part() - { - return "multi"; - } - }; - - // set - template - class MaybeMap : public Base - { - public: - using T = void; - using Value = typename Base::Key; - using Values = std::vector ; - - static typename Base::Key const& extract (Value const& value) - { - return value; - } - - static Values values() - { - Values v { - "apple", - "banana", - "cherry", - "grape", - "orange", - }; - return v; - }; - - protected: - static std::string name_map_part() - { - return "set"; - } - }; - - // map - template - class MaybeMap : public Base - { - public: - using T = int; - using Value = std::pair ; - using Values = std::vector ; - - static typename Base::Key const& extract (Value const& value) - { - return value.first; - } - - static Values values() - { - Values v { - std::make_pair ("apple", 1), - std::make_pair ("banana", 2), - std::make_pair ("cherry", 3), - std::make_pair ("grape", 4), - std::make_pair ("orange", 5) - }; - return v; - }; - - protected: - static std::string name_map_part() - { - return "map"; - } - }; - - //-------------------------------------------------------------------------- - - // ordered - template < - class Base, - bool IsUnordered = Base::is_unordered::value - > - struct ContType - { - template < - class Compare = std::less , - class Allocator = std::allocator - > - using Cont = detail::aged_ordered_container < - Base::is_multi::value, Base::is_map::value, typename Base::Key, - typename Base::T, typename Base::Clock, Compare, Allocator>; - }; - - // unordered - template < - class Base - > - struct ContType - { - template < - class Hash = std::hash , - class KeyEqual = std::equal_to , - class Allocator = std::allocator - > - using Cont = detail::aged_unordered_container < - Base::is_multi::value, Base::is_map::value, - typename Base::Key, typename Base::T, typename Base::Clock, - Hash, KeyEqual, Allocator>; - }; - - //-------------------------------------------------------------------------- - - struct TestTraitsBase - { - using Key = std::string; - using Clock = std::chrono::steady_clock; - using ManualClock = manual_clock; - }; - - template - struct TestTraitsHelper - : MaybeUnordered , IsMulti>, IsUnordered> - { - private: - using Base = MaybeUnordered , IsMulti>, IsUnordered>; - - public: - using typename Base::Key; - - using is_unordered = std::integral_constant ; - using is_multi = std::integral_constant ; - using is_map = std::integral_constant ; - - using Alloc = std::allocator ; - using MyAlloc = AllocT ; - - static std::string name() - { - return std::string ("aged_") + - Base::name_ordered_part() + - Base::name_multi_part() + - Base::name_map_part(); - } - }; - - template - struct TestTraits - : TestTraitsHelper - , ContType > - { - }; - - template - static std::string name (Cont const&) - { - return TestTraits < - Cont::is_unordered, - Cont::is_multi, - Cont::is_map>::name(); - } - - template - struct equal_value - { - bool operator() (typename Traits::Value const& lhs, - typename Traits::Value const& rhs) - { - return Traits::extract (lhs) == Traits::extract (rhs); - } - }; - - template - static - std::vector - make_list (Cont const& c) - { - return std::vector ( - c.begin(), c.end()); - } - - //-------------------------------------------------------------------------- - - template < - class Container, - class Values - > - typename std::enable_if < - Container::is_map::value && ! Container::is_multi::value>::type - checkMapContents (Container& c, Values const& v); - - template < - class Container, - class Values - > - typename std::enable_if ::type - checkMapContents (Container, Values const&) - { - } - - // unordered - template < - class C, - class Values - > - typename std::enable_if < - std::remove_reference ::type::is_unordered::value>::type - checkUnorderedContentsRefRef (C&& c, Values const& v); - - template < - class C, - class Values - > - typename std::enable_if ::type::is_unordered::value>::type - checkUnorderedContentsRefRef (C&&, Values const&) - { - } - - template - void checkContentsRefRef (C&& c, Values const& v); - - template - void checkContents (Cont& c, Values const& v); - - template - void checkContents (Cont& c); - - //-------------------------------------------------------------------------- - - // ordered - template - typename std::enable_if ::type - testConstructEmpty (); - - // unordered - template - typename std::enable_if ::type - testConstructEmpty (); - - // ordered - template - typename std::enable_if ::type - testConstructRange (); - - // unordered - template - typename std::enable_if ::type - testConstructRange (); - - // ordered - template - typename std::enable_if ::type - testConstructInitList (); - - // unordered - template - typename std::enable_if ::type - testConstructInitList (); - - //-------------------------------------------------------------------------- - - template - void - testCopyMove (); - - //-------------------------------------------------------------------------- - - template - void - testIterator (); - - // Unordered containers don't have reverse iterators - template - typename std::enable_if ::type - testReverseIterator(); - - template - typename std::enable_if ::type - testReverseIterator() - { - } - - //-------------------------------------------------------------------------- - - template - void checkInsertCopy (Container& c, Values const& v); - - template - void checkInsertMove (Container& c, Values const& v); - - template - void checkInsertHintCopy (Container& c, Values const& v); - - template - void checkInsertHintMove (Container& c, Values const& v); - - template - void checkEmplace (Container& c, Values const& v); - - template - void checkEmplaceHint (Container& c, Values const& v); - - template - void testModifiers(); - - //-------------------------------------------------------------------------- - - template - void - testChronological (); - - //-------------------------------------------------------------------------- - - // map, unordered_map - template - typename std::enable_if ::type - testArrayCreate(); - - template - typename std::enable_if ::type - testArrayCreate() - { - } - - //-------------------------------------------------------------------------- - - // Helpers for erase tests - template - void reverseFillAgedContainer(Container& c, Values const& v); - - template - Iter nextToEndIter (Iter const beginIter, Iter const endItr); - - //-------------------------------------------------------------------------- - - template - bool doElementErase (Container& c, Iter const beginItr, Iter const endItr); - - template - void testElementErase(); - - //-------------------------------------------------------------------------- - - template - void doRangeErase (Container& c, BeginEndSrc const& beginEndSrc); - - template - void testRangeErase(); - - //-------------------------------------------------------------------------- - - // ordered - template - typename std::enable_if ::type - testCompare (); - - template - typename std::enable_if ::type - testCompare () - { - } - - //-------------------------------------------------------------------------- - - // ordered - template - typename std::enable_if ::type - testObservers(); - - // unordered - template - typename std::enable_if ::type - testObservers(); - - //-------------------------------------------------------------------------- - - template - void testMaybeUnorderedMultiMap (); - - template - void testMaybeUnorderedMulti(); - - template - void testMaybeUnordered(); -}; - -//------------------------------------------------------------------------------ - -// Check contents via at() and operator[] -// map, unordered_map -template < - class Container, - class Values -> -typename std::enable_if < - Container::is_map::value && ! Container::is_multi::value>::type -aged_associative_container_test_base:: -checkMapContents (Container& c, Values const& v) -{ - if (v.empty()) - { - expect (c.empty()); - expect (c.size() == 0); - return; - } - - try - { - // Make sure no exception is thrown - for (auto const& e : v) - c.at (e.first); - for (auto const& e : v) - expect (c.operator[](e.first) == e.second); - } - catch (std::out_of_range const&) - { - fail ("caught exception"); - } -} - -// unordered -template < - class C, - class Values -> -typename std::enable_if < - std::remove_reference ::type::is_unordered::value>::type -aged_associative_container_test_base:: -checkUnorderedContentsRefRef (C&& c, Values const& v) -{ - using Cont = typename std::remove_reference ::type; - using Traits = TestTraits < - Cont::is_unordered::value, - Cont::is_multi::value, - Cont::is_map::value - >; - using size_type = typename Cont::size_type; - auto const hash (c.hash_function()); - auto const key_eq (c.key_eq()); - for (size_type i (0); i < c.bucket_count(); ++i) - { - auto const last (c.end(i)); - for (auto iter (c.begin (i)); iter != last; ++iter) - { - auto const match (std::find_if (v.begin(), v.end(), - [iter](typename Values::value_type const& e) - { - return Traits::extract (*iter) == - Traits::extract (e); - })); - expect (match != v.end()); - expect (key_eq (Traits::extract (*iter), - Traits::extract (*match))); - expect (hash (Traits::extract (*iter)) == - hash (Traits::extract (*match))); - } - } -} - -template -void -aged_associative_container_test_base:: -checkContentsRefRef (C&& c, Values const& v) -{ - using Cont = typename std::remove_reference ::type; - using Traits = TestTraits < - Cont::is_unordered::value, - Cont::is_multi::value, - Cont::is_map::value - >; - using size_type = typename Cont::size_type; - - expect (c.size() == v.size()); - expect (size_type (std::distance ( - c.begin(), c.end())) == v.size()); - expect (size_type (std::distance ( - c.cbegin(), c.cend())) == v.size()); - expect (size_type (std::distance ( - c.chronological.begin(), c.chronological.end())) == v.size()); - expect (size_type (std::distance ( - c.chronological.cbegin(), c.chronological.cend())) == v.size()); - expect (size_type (std::distance ( - c.chronological.rbegin(), c.chronological.rend())) == v.size()); - expect (size_type (std::distance ( - c.chronological.crbegin(), c.chronological.crend())) == v.size()); - - checkUnorderedContentsRefRef (c, v); -} - -template -void -aged_associative_container_test_base:: -checkContents (Cont& c, Values const& v) -{ - checkContentsRefRef (c, v); - checkContentsRefRef (const_cast (c), v); - checkMapContents (c, v); -} - -template -void -aged_associative_container_test_base:: -checkContents (Cont& c) -{ - using Traits = TestTraits < - Cont::is_unordered::value, - Cont::is_multi::value, - Cont::is_map::value - >; - using Values = typename Traits::Values; - checkContents (c, Values()); -} - -//------------------------------------------------------------------------------ -// -// Construction -// -//------------------------------------------------------------------------------ - -// ordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testConstructEmpty () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Key = typename Traits::Key; - using T = typename Traits::T; - using Clock = typename Traits::Clock; - using Comp = typename Traits::Comp; - using Alloc = typename Traits::Alloc; - using MyComp = typename Traits::MyComp; - using MyAlloc = typename Traits::MyAlloc; - typename Traits::ManualClock clock; - - //testcase (Traits::name() + " empty"); - testcase ("empty"); - - { - typename Traits::template Cont c ( - clock); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyComp(1)); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyAlloc(1)); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyComp(1), MyAlloc(1)); - checkContents (c); - } -} - -// unordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testConstructEmpty () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Key = typename Traits::Key; - using T = typename Traits::T; - using Clock = typename Traits::Clock; - using Hash = typename Traits::Hash; - using Equal = typename Traits::Equal; - using Alloc = typename Traits::Alloc; - using MyHash = typename Traits::MyHash; - using MyEqual = typename Traits::MyEqual; - using MyAlloc = typename Traits::MyAlloc; - typename Traits::ManualClock clock; - - //testcase (Traits::name() + " empty"); - testcase ("empty"); - { - typename Traits::template Cont c ( - clock); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyHash(1)); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyEqual (1)); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyAlloc (1)); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyHash(1), MyEqual(1)); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyHash(1), MyAlloc(1)); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyEqual(1), MyAlloc(1)); - checkContents (c); - } - - { - typename Traits::template Cont c ( - clock, MyHash(1), MyEqual(1), MyAlloc(1)); - checkContents (c); - } -} - -// ordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testConstructRange () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Key = typename Traits::Key; - using T = typename Traits::T; - using Clock = typename Traits::Clock; - using Comp = typename Traits::Comp; - using Alloc = typename Traits::Alloc; - using MyComp = typename Traits::MyComp; - using MyAlloc = typename Traits::MyAlloc; - typename Traits::ManualClock clock; - auto const v (Traits::values()); - - //testcase (Traits::name() + " range"); - testcase ("range"); - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyComp(1)); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyAlloc(1)); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyComp(1), MyAlloc(1)); - checkContents (c, v); - - } - - // swap - - { - typename Traits::template Cont c1 ( - v.begin(), v.end(), - clock); - typename Traits::template Cont c2 ( - clock); - std::swap (c1, c2); - checkContents (c2, v); - } -} - -// unordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testConstructRange () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Key = typename Traits::Key; - using T = typename Traits::T; - using Clock = typename Traits::Clock; - using Hash = typename Traits::Hash; - using Equal = typename Traits::Equal; - using Alloc = typename Traits::Alloc; - using MyHash = typename Traits::MyHash; - using MyEqual = typename Traits::MyEqual; - using MyAlloc = typename Traits::MyAlloc; - typename Traits::ManualClock clock; - auto const v (Traits::values()); - - //testcase (Traits::name() + " range"); - testcase ("range"); - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyHash(1)); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyEqual (1)); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyAlloc (1)); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyHash(1), MyEqual(1)); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyHash(1), MyAlloc(1)); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyEqual(1), MyAlloc(1)); - checkContents (c, v); - } - - { - typename Traits::template Cont c ( - v.begin(), v.end(), - clock, MyHash(1), MyEqual(1), MyAlloc(1)); - checkContents (c, v); - } -} - -// ordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testConstructInitList () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Key = typename Traits::Key; - using T = typename Traits::T; - using Clock = typename Traits::Clock; - using Comp = typename Traits::Comp; - using Alloc = typename Traits::Alloc; - using MyComp = typename Traits::MyComp; - using MyAlloc = typename Traits::MyAlloc; - typename Traits::ManualClock clock; - - //testcase (Traits::name() + " init-list"); - testcase ("init-list"); - - // VFALCO TODO - - pass(); -} - -// unordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testConstructInitList () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Key = typename Traits::Key; - using T = typename Traits::T; - using Clock = typename Traits::Clock; - using Hash = typename Traits::Hash; - using Equal = typename Traits::Equal; - using Alloc = typename Traits::Alloc; - using MyHash = typename Traits::MyHash; - using MyEqual = typename Traits::MyEqual; - using MyAlloc = typename Traits::MyAlloc; - typename Traits::ManualClock clock; - - //testcase (Traits::name() + " init-list"); - testcase ("init-list"); - - // VFALCO TODO - pass(); -} - -//------------------------------------------------------------------------------ -// -// Copy/Move construction and assign -// -//------------------------------------------------------------------------------ - -template -void -aged_associative_container_test_base:: -testCopyMove () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Alloc = typename Traits::Alloc; - typename Traits::ManualClock clock; - auto const v (Traits::values()); - - //testcase (Traits::name() + " copy/move"); - testcase ("copy/move"); - - // copy - - { - typename Traits::template Cont <> c ( - v.begin(), v.end(), clock); - typename Traits::template Cont <> c2 (c); - checkContents (c, v); - checkContents (c2, v); - expect (c == c2); - unexpected (c != c2); - } - - { - typename Traits::template Cont <> c ( - v.begin(), v.end(), clock); - typename Traits::template Cont <> c2 (c, Alloc()); - checkContents (c, v); - checkContents (c2, v); - expect (c == c2); - unexpected (c != c2); - } - - { - typename Traits::template Cont <> c ( - v.begin(), v.end(), clock); - typename Traits::template Cont <> c2 ( - clock); - c2 = c; - checkContents (c, v); - checkContents (c2, v); - expect (c == c2); - unexpected (c != c2); - } - - // move - - { - typename Traits::template Cont <> c ( - v.begin(), v.end(), clock); - typename Traits::template Cont <> c2 ( - std::move (c)); - checkContents (c2, v); - } - - { - typename Traits::template Cont <> c ( - v.begin(), v.end(), clock); - typename Traits::template Cont <> c2 ( - std::move (c), Alloc()); - checkContents (c2, v); - } - - { - typename Traits::template Cont <> c ( - v.begin(), v.end(), clock); - typename Traits::template Cont <> c2 ( - clock); - c2 = std::move (c); - checkContents (c2, v); - } -} - -//------------------------------------------------------------------------------ -// -// Iterator construction and assignment -// -//------------------------------------------------------------------------------ - -template -void -aged_associative_container_test_base:: -testIterator() -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Alloc = typename Traits::Alloc; - typename Traits::ManualClock clock; - auto const v (Traits::values()); - - //testcase (Traits::name() + " iterators"); - testcase ("iterator"); - - typename Traits::template Cont <> c {clock}; - - using iterator = decltype (c.begin()); - using const_iterator = decltype (c.cbegin()); - - // Should be able to construct or assign an iterator from an iterator. - iterator nnIt_0 {c.begin()}; - iterator nnIt_1 {nnIt_0}; - expect (nnIt_0 == nnIt_1, "iterator constructor failed"); - iterator nnIt_2; - nnIt_2 = nnIt_1; - expect (nnIt_1 == nnIt_2, "iterator assignment failed"); - - // Should be able to construct or assign a const_iterator from a - // const_iterator. - const_iterator ccIt_0 {c.cbegin()}; - const_iterator ccIt_1 {ccIt_0}; - expect (ccIt_0 == ccIt_1, "const_iterator constructor failed"); - const_iterator ccIt_2; - ccIt_2 = ccIt_1; - expect (ccIt_1 == ccIt_2, "const_iterator assignment failed"); - - // Comparison between iterator and const_iterator is okay - expect (nnIt_0 == ccIt_0, - "Comparing an iterator to a const_iterator failed"); - expect (ccIt_1 == nnIt_1, - "Comparing a const_iterator to an iterator failed"); - - // Should be able to construct a const_iterator from an iterator. - const_iterator ncIt_3 {c.begin()}; - const_iterator ncIt_4 {nnIt_0}; - expect (ncIt_3 == ncIt_4, - "const_iterator construction from iterator failed"); - const_iterator ncIt_5; - ncIt_5 = nnIt_2; - expect (ncIt_5 == ncIt_4, - "const_iterator assignment from iterator failed"); - - // None of these should compile because they construct or assign to a - // non-const iterator with a const_iterator. - -// iterator cnIt_0 {c.cbegin()}; - -// iterator cnIt_1 {ccIt_0}; - -// iterator cnIt_2; -// cnIt_2 = ccIt_2; -} - -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testReverseIterator() -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - using Alloc = typename Traits::Alloc; - typename Traits::ManualClock clock; - auto const v (Traits::values()); - - //testcase (Traits::name() + " reverse_iterators"); - testcase ("reverse_iterator"); - - typename Traits::template Cont <> c {clock}; - - using iterator = decltype (c.begin()); - using const_iterator = decltype (c.cbegin()); - using reverse_iterator = decltype (c.rbegin()); - using const_reverse_iterator = decltype (c.crbegin()); - - // Naming decoder ring - // constructed from ------+ +----- constructed type - // /\/\ -- character pairs - // xAyBit - // r (reverse) or f (forward)--^-^ - // ^-^------ C (const) or N (non-const) - - // Should be able to construct or assign a reverse_iterator from a - // reverse_iterator. - reverse_iterator rNrNit_0 {c.rbegin()}; - reverse_iterator rNrNit_1 {rNrNit_0}; - expect (rNrNit_0 == rNrNit_1, "reverse_iterator constructor failed"); - reverse_iterator xXrNit_2; - xXrNit_2 = rNrNit_1; - expect (rNrNit_1 == xXrNit_2, "reverse_iterator assignment failed"); - - // Should be able to construct or assign a const_reverse_iterator from a - // const_reverse_iterator - const_reverse_iterator rCrCit_0 {c.crbegin()}; - const_reverse_iterator rCrCit_1 {rCrCit_0}; - expect (rCrCit_0 == rCrCit_1, "reverse_iterator constructor failed"); - const_reverse_iterator xXrCit_2; - xXrCit_2 = rCrCit_1; - expect (rCrCit_1 == xXrCit_2, "reverse_iterator assignment failed"); - - // Comparison between reverse_iterator and const_reverse_iterator is okay - expect (rNrNit_0 == rCrCit_0, - "Comparing an iterator to a const_iterator failed"); - expect (rCrCit_1 == rNrNit_1, - "Comparing a const_iterator to an iterator failed"); - - // Should be able to construct or assign a const_reverse_iterator from a - // reverse_iterator - const_reverse_iterator rNrCit_0 {c.rbegin()}; - const_reverse_iterator rNrCit_1 {rNrNit_0}; - expect (rNrCit_0 == rNrCit_1, - "const_reverse_iterator construction from reverse_iterator failed"); - xXrCit_2 = rNrNit_1; - expect (rNrCit_1 == xXrCit_2, - "const_reverse_iterator assignment from reverse_iterator failed"); - - // The standard allows these conversions: - // o reverse_iterator is explicitly constructible from iterator. - // o const_reverse_iterator is explicitly constructible from const_iterator. - // Should be able to construct or assign reverse_iterators from - // non-reverse iterators. - reverse_iterator fNrNit_0 {c.begin()}; - const_reverse_iterator fNrCit_0 {c.begin()}; - expect (fNrNit_0 == fNrCit_0, - "reverse_iterator construction from iterator failed"); - const_reverse_iterator fCrCit_0 {c.cbegin()}; - expect (fNrCit_0 == fCrCit_0, - "const_reverse_iterator construction from const_iterator failed"); - - // None of these should compile because they construct a non-reverse - // iterator from a reverse_iterator. -// iterator rNfNit_0 {c.rbegin()}; -// const_iterator rNfCit_0 {c.rbegin()}; -// const_iterator rCfCit_0 {c.crbegin()}; - - // You should not be able to assign an iterator to a reverse_iterator or - // vise-versa. So the following lines should not compile. - iterator xXfNit_0; -// xXfNit_0 = xXrNit_2; -// xXrNit_2 = xXfNit_0; -} - -//------------------------------------------------------------------------------ -// -// Modifiers -// -//------------------------------------------------------------------------------ - - -template -void -aged_associative_container_test_base:: -checkInsertCopy (Container& c, Values const& v) -{ - for (auto const& e : v) - c.insert (e); - checkContents (c, v); -} - -template -void -aged_associative_container_test_base:: -checkInsertMove (Container& c, Values const& v) -{ - Values v2 (v); - for (auto& e : v2) - c.insert (std::move (e)); - checkContents (c, v); -} - -template -void -aged_associative_container_test_base:: -checkInsertHintCopy (Container& c, Values const& v) -{ - for (auto const& e : v) - c.insert (c.cend(), e); - checkContents (c, v); -} - -template -void -aged_associative_container_test_base:: -checkInsertHintMove (Container& c, Values const& v) -{ - Values v2 (v); - for (auto& e : v2) - c.insert (c.cend(), std::move (e)); - checkContents (c, v); -} - -template -void -aged_associative_container_test_base:: -checkEmplace (Container& c, Values const& v) -{ - for (auto const& e : v) - c.emplace (e); - checkContents (c, v); -} - -template -void -aged_associative_container_test_base:: -checkEmplaceHint (Container& c, Values const& v) -{ - for (auto const& e : v) - c.emplace_hint (c.cend(), e); - checkContents (c, v); -} - -template -void -aged_associative_container_test_base:: -testModifiers() -{ - using Traits = TestTraits ; - typename Traits::ManualClock clock; - auto const v (Traits::values()); - auto const l (make_list (v)); - - //testcase (Traits::name() + " modify"); - testcase ("modify"); - - { - typename Traits::template Cont <> c (clock); - checkInsertCopy (c, v); - } - - { - typename Traits::template Cont <> c (clock); - checkInsertCopy (c, l); - } - - { - typename Traits::template Cont <> c (clock); - checkInsertMove (c, v); - } - - { - typename Traits::template Cont <> c (clock); - checkInsertMove (c, l); - } - - { - typename Traits::template Cont <> c (clock); - checkInsertHintCopy (c, v); - } - - { - typename Traits::template Cont <> c (clock); - checkInsertHintCopy (c, l); - } - - { - typename Traits::template Cont <> c (clock); - checkInsertHintMove (c, v); - } - - { - typename Traits::template Cont <> c (clock); - checkInsertHintMove (c, l); - } -} - -//------------------------------------------------------------------------------ -// -// Chronological ordering -// -//------------------------------------------------------------------------------ - -template -void -aged_associative_container_test_base:: -testChronological () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - typename Traits::ManualClock clock; - auto const v (Traits::values()); - - //testcase (Traits::name() + " chronological"); - testcase ("chronological"); - - typename Traits::template Cont <> c ( - v.begin(), v.end(), clock); - - expect (std::equal ( - c.chronological.cbegin(), c.chronological.cend(), - v.begin(), v.end(), equal_value ())); - - // Test touch() with a non-const iterator. - for (auto iter (v.crbegin()); iter != v.crend(); ++iter) - { - using iterator = typename decltype (c)::iterator; - iterator found (c.find (Traits::extract (*iter))); - - expect (found != c.cend()); - if (found == c.cend()) - return; - c.touch (found); - } - - expect (std::equal ( - c.chronological.cbegin(), c.chronological.cend(), - v.crbegin(), v.crend(), equal_value ())); - - // Test touch() with a const_iterator - for (auto iter (v.cbegin()); iter != v.cend(); ++iter) - { - using const_iterator = typename decltype (c)::const_iterator; - const_iterator found (c.find (Traits::extract (*iter))); - - expect (found != c.cend()); - if (found == c.cend()) - return; - c.touch (found); - } - - expect (std::equal ( - c.chronological.cbegin(), c.chronological.cend(), - v.cbegin(), v.cend(), equal_value ())); - - { - // Because touch (reverse_iterator pos) is not allowed, the following - // lines should not compile for any aged_container type. -// c.touch (c.rbegin()); -// c.touch (c.crbegin()); - } -} - -//------------------------------------------------------------------------------ -// -// Element creation via operator[] -// -//------------------------------------------------------------------------------ - -// map, unordered_map -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testArrayCreate() -{ - using Traits = TestTraits ; - typename Traits::ManualClock clock; - auto v (Traits::values()); - - //testcase (Traits::name() + " array create"); - testcase ("array create"); - - { - // Copy construct key - typename Traits::template Cont <> c (clock); - for (auto e : v) - c [e.first] = e.second; - checkContents (c, v); - } - - { - // Move construct key - typename Traits::template Cont <> c (clock); - for (auto e : v) - c [std::move (e.first)] = e.second; - checkContents (c, v); - } -} - -//------------------------------------------------------------------------------ -// -// Helpers for erase tests -// -//------------------------------------------------------------------------------ - -template -void -aged_associative_container_test_base:: -reverseFillAgedContainer (Container& c, Values const& values) -{ - // Just in case the passed in container was not empty. - c.clear(); - - // c.clock() returns an abstract_clock, so dynamic_cast to manual_clock. - // VFALCO NOTE This is sketchy - using ManualClock = TestTraitsBase::ManualClock; - ManualClock& clk (dynamic_cast (c.clock())); - clk.set (0); - - Values rev (values); - std::sort (rev.begin (), rev.end ()); - std::reverse (rev.begin (), rev.end ()); - for (auto& v : rev) - { - // Add values in reverse order so they are reversed chronologically. - ++clk; - c.insert (v); - } -} - -// Get one iterator before endIter. We have to use operator++ because you -// cannot use operator-- with unordered container iterators. -template -Iter -aged_associative_container_test_base:: -nextToEndIter (Iter beginIter, Iter const endIter) -{ - if (beginIter == endIter) - { - fail ("Internal test failure. Cannot advance beginIter"); - return beginIter; - } - - // - Iter nextToEnd = beginIter; - do - { - nextToEnd = beginIter++; - } while (beginIter != endIter); - return nextToEnd; -} - -// Implementation for the element erase tests -// -// This test accepts: -// o the container from which we will erase elements -// o iterators into that container defining the range of the erase -// -// This implementation does not declare a pass, since it wants to allow -// the caller to examine the size of the container and the returned iterator -// -// Note that this test works on the aged_associative containers because an -// erase only invalidates references and iterators to the erased element -// (see 23.2.4/13). Therefore the passed-in end iterator stays valid through -// the whole test. -template -bool aged_associative_container_test_base:: -doElementErase (Container& c, Iter const beginItr, Iter const endItr) -{ - auto it (beginItr); - size_t count = c.size(); - while (it != endItr) - { - auto expectIt = it; - ++expectIt; - it = c.erase (it); - - if (it != expectIt) - { - fail ("Unexpected returned iterator from element erase"); - return false; - } - - --count; - if (count != c.size()) - { - fail ("Failed to erase element"); - return false; - } - - if (c.empty ()) - { - if (it != endItr) - { - fail ("Erase of last element didn't produce end"); - return false; - } - } - } - return true; -} - -//------------------------------------------------------------------------------ -// -// Erase of individual elements -// -//------------------------------------------------------------------------------ - -template -void -aged_associative_container_test_base:: -testElementErase () -{ - using Traits = TestTraits ; - - //testcase (Traits::name() + " element erase" - testcase ("element erase"); - - // Make and fill the container - typename Traits::ManualClock clock; - typename Traits::template Cont <> c {clock}; - reverseFillAgedContainer (c, Traits::values()); - - { - // Test standard iterators - auto tempContainer (c); - if (! doElementErase (tempContainer, - tempContainer.cbegin(), tempContainer.cend())) - return; // Test failed - - expect (tempContainer.empty(), "Failed to erase all elements"); - pass(); - } - { - // Test chronological iterators - auto tempContainer (c); - auto& chron (tempContainer.chronological); - if (! doElementErase (tempContainer, chron.begin(), chron.end())) - return; // Test failed - - expect (tempContainer.empty(), - "Failed to chronologically erase all elements"); - pass(); - } - { - // Test standard iterator partial erase - auto tempContainer (c); - expect (tempContainer.size() > 2, - "Internal failure. Container too small."); - if (! doElementErase (tempContainer, ++tempContainer.begin(), - nextToEndIter (tempContainer.begin(), tempContainer.end()))) - return; // Test failed - - expect (tempContainer.size() == 2, - "Failed to erase expected number of elements"); - pass(); - } - { - // Test chronological iterator partial erase - auto tempContainer (c); - expect (tempContainer.size() > 2, - "Internal failure. Container too small."); - auto& chron (tempContainer.chronological); - if (! doElementErase (tempContainer, ++chron.begin(), - nextToEndIter (chron.begin(), chron.end()))) - return; // Test failed - - expect (tempContainer.size() == 2, - "Failed to chronologically erase expected number of elements"); - pass(); - } - { - auto tempContainer (c); - expect (tempContainer.size() > 4, - "Internal failure. Container too small."); - // erase(reverse_iterator) is not allowed. None of the following - // should compile for any aged_container type. -// c.erase (c.rbegin()); -// c.erase (c.crbegin()); -// c.erase(c.rbegin(), ++c.rbegin()); -// c.erase(c.crbegin(), ++c.crbegin()); - } -} - -// Implementation for the range erase tests -// -// This test accepts: -// -// o A container with more than 2 elements and -// o An object to ask for begin() and end() iterators in the passed container -// -// This peculiar interface allows either the container itself to be passed as -// the second argument or the container's "chronological" element. Both -// sources of iterators need to be tested on the container. -// -// The test locates iterators such that a range-based delete leaves the first -// and last elements in the container. It then validates that the container -// ended up with the expected contents. -// -template -void -aged_associative_container_test_base:: -doRangeErase (Container& c, BeginEndSrc const& beginEndSrc) -{ - expect (c.size () > 2, - "Internal test failure. Container must have more than 2 elements"); - auto itBeginPlusOne (beginEndSrc.begin ()); - auto const valueFront = *itBeginPlusOne; - ++itBeginPlusOne; - - // Get one iterator before end() - auto itBack (nextToEndIter (itBeginPlusOne, beginEndSrc.end ())); - auto const valueBack = *itBack; - - // Erase all elements but first and last - auto const retIter = c.erase (itBeginPlusOne, itBack); - - expect (c.size() == 2, - "Unexpected size for range-erased container"); - - expect (valueFront == *(beginEndSrc.begin()), - "Unexpected first element in range-erased container"); - - expect (valueBack == *(++beginEndSrc.begin()), - "Unexpected last element in range-erased container"); - - expect (retIter == (++beginEndSrc.begin()), - "Unexpected return iterator from erase"); - - pass (); -} - -//------------------------------------------------------------------------------ -// -// Erase range of elements -// -//------------------------------------------------------------------------------ - -template -void -aged_associative_container_test_base:: -testRangeErase () -{ - using Traits = TestTraits ; - - //testcase (Traits::name() + " element erase" - testcase ("range erase"); - - // Make and fill the container - typename Traits::ManualClock clock; - typename Traits::template Cont <> c {clock}; - reverseFillAgedContainer (c, Traits::values()); - - // Not bothering to test range erase with reverse iterators. - { - auto tempContainer (c); - doRangeErase (tempContainer, tempContainer); - } - { - auto tempContainer (c); - doRangeErase (tempContainer, tempContainer.chronological); - } -} - -//------------------------------------------------------------------------------ -// -// Container-wide comparison -// -//------------------------------------------------------------------------------ - -// ordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testCompare () -{ - using Traits = TestTraits ; - using Value = typename Traits::Value; - typename Traits::ManualClock clock; - auto const v (Traits::values()); - - //testcase (Traits::name() + " array create"); - testcase ("array create"); - - typename Traits::template Cont <> c1 ( - v.begin(), v.end(), clock); - - typename Traits::template Cont <> c2 ( - v.begin(), v.end(), clock); - c2.erase (c2.cbegin()); - - expect (c1 != c2); - unexpected (c1 == c2); - expect (c1 < c2); - expect (c1 <= c2); - unexpected (c1 > c2); - unexpected (c1 >= c2); -} - -//------------------------------------------------------------------------------ -// -// Observers -// -//------------------------------------------------------------------------------ - -// ordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testObservers() -{ - using Traits = TestTraits ; - typename Traits::ManualClock clock; - - //testcase (Traits::name() + " observers"); - testcase ("observers"); - - typename Traits::template Cont <> c (clock); - c.key_comp(); - c.value_comp(); - - pass(); -} - -// unordered -template -typename std::enable_if ::type -aged_associative_container_test_base:: -testObservers() -{ - using Traits = TestTraits ; - typename Traits::ManualClock clock; - - //testcase (Traits::name() + " observers"); - testcase ("observers"); - - typename Traits::template Cont <> c (clock); - c.hash_function(); - c.key_eq(); - - pass(); -} - -//------------------------------------------------------------------------------ -// -// Matrix -// -//------------------------------------------------------------------------------ - -template -void -aged_associative_container_test_base:: -testMaybeUnorderedMultiMap () -{ - using Traits = TestTraits ; - - testConstructEmpty (); - testConstructRange (); - testConstructInitList (); - testCopyMove (); - testIterator (); - testReverseIterator (); - testModifiers (); - testChronological (); - testArrayCreate (); - testElementErase (); - testRangeErase (); - testCompare (); - testObservers (); -} - -//------------------------------------------------------------------------------ - -class aged_set_test : public aged_associative_container_test_base -{ -public: - // Compile time checks - - using Key = std::string; - using T = int; - - static_assert (std::is_same < - aged_set , - detail::aged_ordered_container >::value, - "bad alias: aged_set"); - - static_assert (std::is_same < - aged_multiset , - detail::aged_ordered_container >::value, - "bad alias: aged_multiset"); - - static_assert (std::is_same < - aged_map , - detail::aged_ordered_container >::value, - "bad alias: aged_map"); - - static_assert (std::is_same < - aged_multimap , - detail::aged_ordered_container >::value, - "bad alias: aged_multimap"); - - static_assert (std::is_same < - aged_unordered_set , - detail::aged_unordered_container >::value, - "bad alias: aged_unordered_set"); - - static_assert (std::is_same < - aged_unordered_multiset , - detail::aged_unordered_container >::value, - "bad alias: aged_unordered_multiset"); - - static_assert (std::is_same < - aged_unordered_map , - detail::aged_unordered_container >::value, - "bad alias: aged_unordered_map"); - - static_assert (std::is_same < - aged_unordered_multimap , - detail::aged_unordered_container >::value, - "bad alias: aged_unordered_multimap"); - - void run () - { - testMaybeUnorderedMultiMap (); - } -}; - -class aged_map_test : public aged_associative_container_test_base -{ -public: - void run () - { - testMaybeUnorderedMultiMap (); - } -}; - -class aged_multiset_test : public aged_associative_container_test_base -{ -public: - void run () - { - testMaybeUnorderedMultiMap (); - } -}; - -class aged_multimap_test : public aged_associative_container_test_base -{ -public: - void run () - { - testMaybeUnorderedMultiMap (); - } -}; - - -class aged_unordered_set_test : public aged_associative_container_test_base -{ -public: - void run () - { - testMaybeUnorderedMultiMap (); - } -}; - -class aged_unordered_map_test : public aged_associative_container_test_base -{ -public: - void run () - { - testMaybeUnorderedMultiMap (); - } -}; - -class aged_unordered_multiset_test : public aged_associative_container_test_base -{ -public: - void run () - { - testMaybeUnorderedMultiMap (); - } -}; - -class aged_unordered_multimap_test : public aged_associative_container_test_base -{ -public: - void run () - { - testMaybeUnorderedMultiMap (); - } -}; - -BEAST_DEFINE_TESTSUITE(aged_set,container,beast); -BEAST_DEFINE_TESTSUITE(aged_map,container,beast); -BEAST_DEFINE_TESTSUITE(aged_multiset,container,beast); -BEAST_DEFINE_TESTSUITE(aged_multimap,container,beast); -BEAST_DEFINE_TESTSUITE(aged_unordered_set,container,beast); -BEAST_DEFINE_TESTSUITE(aged_unordered_map,container,beast); -BEAST_DEFINE_TESTSUITE(aged_unordered_multiset,container,beast); -BEAST_DEFINE_TESTSUITE(aged_unordered_multimap,container,beast); - -} // namespace beast diff --git a/beast/crypto/Crypto.unity.cpp b/beast/crypto/Crypto.unity.cpp deleted file mode 100644 index b2cc65d77b..0000000000 --- a/beast/crypto/Crypto.unity.cpp +++ /dev/null @@ -1,24 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include diff --git a/beast/crypto/tests/base64.test.cpp b/beast/crypto/tests/beast_base64_test.cpp similarity index 100% rename from beast/crypto/tests/base64.test.cpp rename to beast/crypto/tests/beast_base64_test.cpp diff --git a/beast/utility/empty_base_optimization.h b/beast/empty_base_optimization.h similarity index 95% rename from beast/utility/empty_base_optimization.h rename to beast/empty_base_optimization.h index 22e19e0d35..199021bad4 100644 --- a/beast/utility/empty_base_optimization.h +++ b/beast/empty_base_optimization.h @@ -18,8 +18,8 @@ */ //============================================================================== -#ifndef BEAST_UTILITY_EMPTY_BASE_OPTIMIZATION_H_INCLUDED -#define BEAST_UTILITY_EMPTY_BASE_OPTIMIZATION_H_INCLUDED +#ifndef BEAST_EMPTY_BASE_OPTIMIZATION_H_INCLUDED +#define BEAST_EMPTY_BASE_OPTIMIZATION_H_INCLUDED #include #include diff --git a/beast/hash/hash_append.h b/beast/hash/hash_append.h index 5cd5c85b1c..861c11ab12 100644 --- a/beast/hash/hash_append.h +++ b/beast/hash/hash_append.h @@ -21,9 +21,8 @@ #ifndef BEAST_HASH_HASH_APPEND_H_INCLUDED #define BEAST_HASH_HASH_APPEND_H_INCLUDED -#include // for constexpr #include -#include +#include #include #include #include diff --git a/beast/utility/meta.h b/beast/hash/meta.h similarity index 98% rename from beast/utility/meta.h rename to beast/hash/meta.h index d0e0f40610..2aaa65b41a 100644 --- a/beast/utility/meta.h +++ b/beast/hash/meta.h @@ -17,8 +17,8 @@ */ //============================================================================== -#ifndef BEAST_UTILITY_META_H_INCLUDED -#define BEAST_UTILITY_META_H_INCLUDED +#ifndef BEAST_HASH_META_H_INCLUDED +#define BEAST_HASH_META_H_INCLUDED #include diff --git a/beast/hash/tests/hash_append_test.cpp b/beast/hash/tests/hash_append_test.cpp index ed9a002411..672082c7f2 100644 --- a/beast/hash/tests/hash_append_test.cpp +++ b/beast/hash/tests/hash_append_test.cpp @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/beast/hash/tests/hash_speed_test.cpp b/beast/hash/tests/hash_speed_test.cpp index 26439479ec..3518e4a8f3 100644 --- a/beast/hash/tests/hash_speed_test.cpp +++ b/beast/hash/tests/hash_speed_test.cpp @@ -17,13 +17,9 @@ */ //============================================================================== -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif #include #include #include -#include #include #include #include @@ -38,6 +34,44 @@ namespace beast { class hash_speed_test : public beast::unit_test::suite { public: + template + static + void + rngfill (void* buffer, std::size_t bytes, + Generator& g) + { + using result_type = + typename Generator::result_type; + while (bytes >= sizeof(result_type)) + { + auto const v = g(); + std::memcpy(buffer, &v, sizeof(v)); + buffer = reinterpret_cast< + std::uint8_t*>(buffer) + sizeof(v); + bytes -= sizeof(v); + } + if (bytes > 0) + { + auto const v = g(); + std::memcpy(buffer, &v, bytes); + } + } + + template > + static + void + rngfill (std::array& a, Generator& g) + { + using result_type = + typename Generator::result_type; + auto i = N / sizeof(result_type); + result_type* p = + reinterpret_cast(a.data()); + while (i--) + *p++ = g(); + } using clock_type = std::chrono::high_resolution_clock; template diff --git a/beast/hash/uhash.h b/beast/hash/uhash.h index 380ff33c76..456c8b2b26 100644 --- a/beast/hash/uhash.h +++ b/beast/hash/uhash.h @@ -21,6 +21,7 @@ #ifndef BEAST_HASH_UHASH_H_INCLUDED #define BEAST_HASH_UHASH_H_INCLUDED +#include #include namespace beast { diff --git a/beast/http/headers.h b/beast/http/headers.h index 098580994d..5c9fc14e1a 100644 --- a/beast/http/headers.h +++ b/beast/http/headers.h @@ -20,7 +20,7 @@ #ifndef BEAST_HTTP_HEADERS_H_INCLUDED #define BEAST_HTTP_HEADERS_H_INCLUDED -#include +#include #include #include #include diff --git a/beast/http/message.h b/beast/http/message.h index 85dfe1913d..bdab45b0a7 100644 --- a/beast/http/message.h +++ b/beast/http/message.h @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/beast/http/method.h b/beast/http/method.h index 0e145eb88f..8144713a39 100644 --- a/beast/http/method.h +++ b/beast/http/method.h @@ -20,6 +20,7 @@ #ifndef BEAST_HTTP_METHOD_H_INCLUDED #define BEAST_HTTP_METHOD_H_INCLUDED +#include #include #include diff --git a/beast/insight/Base.h b/beast/insight/Base.h deleted file mode 100644 index f885d5fa92..0000000000 --- a/beast/insight/Base.h +++ /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. -*/ -//============================================================================== - -#ifndef BEAST_INSIGHT_BASE_H_INCLUDED -#define BEAST_INSIGHT_BASE_H_INCLUDED - -#include - -namespace beast { -namespace insight { - -/** Base for all metrics and hooks. */ -class Base -{ -public: - virtual ~Base () = 0; -}; - -} -} - -#endif diff --git a/beast/insight/BaseImpl.h b/beast/insight/BaseImpl.h deleted file mode 100644 index 4deb3a46be..0000000000 --- a/beast/insight/BaseImpl.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_INSIGHT_BASEIMPL_H_INCLUDED -#define BEAST_INSIGHT_BASEIMPL_H_INCLUDED - -#include -#include -#include -#include - -namespace beast { -namespace insight { - -/** Base for all metrics and hook implementations. */ -class BaseImpl -{ -public: - using ptr = std::shared_ptr ; - - virtual ~BaseImpl () = 0; -}; - -} -} - -#endif diff --git a/beast/insight/Collector.h b/beast/insight/Collector.h deleted file mode 100644 index 954b7fb222..0000000000 --- a/beast/insight/Collector.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_INSIGHT_COLLECTOR_H_INCLUDED -#define BEAST_INSIGHT_COLLECTOR_H_INCLUDED - -#include -#include -#include -#include -#include - -#include - -namespace beast { -namespace insight { - -/** Interface for a manager that allows collection of metrics. - - To export metrics from a class, pass and save a shared_ptr to this - interface in the class constructor. Create the metric objects - as desired (counters, events, gauges, meters, and an optional hook) - using the interface. - - @see Counter, Event, Gauge, Hook, Meter - @see NullCollector, StatsDCollector -*/ -class Collector -{ -public: - using ptr = std::shared_ptr ; - - virtual ~Collector() = 0; - - /** Create a hook. - - A hook is called at each collection interval, on an implementation - defined thread. This is a convenience facility for gathering metrics - in the polling style. The typical usage is to update all the metrics - of interest in the handler. - - Handler will be called with this signature: - void handler (void) - - @see Hook - */ - /** @{ */ - template - Hook make_hook (Handler handler) - { - return make_hook (HookImpl::HandlerType (handler)); - } - - virtual Hook make_hook (HookImpl::HandlerType const& handler) = 0; - /** @} */ - - /** Create a counter with the specified name. - @see Counter - */ - /** @{ */ - virtual Counter make_counter (std::string const& name) = 0; - - Counter make_counter (std::string const& prefix, std::string const& name) - { - if (prefix.empty ()) - return make_counter (name); - return make_counter (prefix + "." + name); - } - /** @} */ - - /** Create an event with the specified name. - @see Event - */ - /** @{ */ - virtual Event make_event (std::string const& name) = 0; - - Event make_event (std::string const& prefix, std::string const& name) - { - if (prefix.empty ()) - return make_event (name); - return make_event (prefix + "." + name); - } - /** @} */ - - /** Create a gauge with the specified name. - @see Gauge - */ - /** @{ */ - virtual Gauge make_gauge (std::string const& name) = 0; - - Gauge make_gauge (std::string const& prefix, std::string const& name) - { - if (prefix.empty ()) - return make_gauge (name); - return make_gauge (prefix + "." + name); - } - /** @} */ - - /** Create a meter with the specified name. - @see Meter - */ - /** @{ */ - virtual Meter make_meter (std::string const& name) = 0; - - Meter make_meter (std::string const& prefix, std::string const& name) - { - if (prefix.empty ()) - return make_meter (name); - return make_meter (prefix + "." + name); - } - /** @} */ -}; - -} -} - -#endif diff --git a/beast/insight/Counter.h b/beast/insight/Counter.h deleted file mode 100644 index 268c639c3e..0000000000 --- a/beast/insight/Counter.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_INSIGHT_COUNTER_H_INCLUDED -#define BEAST_INSIGHT_COUNTER_H_INCLUDED - -#include -#include - -#include - -namespace beast { -namespace insight { - -/** A metric for measuring an integral value. - - A counter is a gauge calculated at the server. The owner of the counter - may increment and decrement the value by an amount. - - This is a lightweight reference wrapper which is cheap to copy and assign. - When the last reference goes away, the metric is no longer collected. -*/ -class Counter : public Base -{ -public: - using value_type = CounterImpl::value_type; - - /** Create a null metric. - A null metric reports no information. - */ - Counter () - { - } - - /** Create the metric reference the specified implementation. - Normally this won't be called directly. Instead, call the appropriate - factory function in the Collector interface. - @see Collector. - */ - explicit Counter (std::shared_ptr const& impl) - : m_impl (impl) - { - } - - /** Increment the counter. */ - /** @{ */ - void - increment (value_type amount) const - { - if (m_impl) - m_impl->increment (amount); - } - - Counter const& - operator+= (value_type amount) const - { - increment (amount); - return *this; - } - - Counter const& - operator-= (value_type amount) const - { - increment (-amount); - return *this; - } - - Counter const& - operator++ () const - { - increment (1); - return *this; - } - - Counter const& - operator++ (int) const - { - increment (1); - return *this; - } - - Counter const& - operator-- () const - { - increment (-1); - return *this; - } - - Counter const& - operator-- (int) const - { - increment (-1); - return *this; - } - /** @} */ - - std::shared_ptr const& - impl () const - { - return m_impl; - } - -private: - std::shared_ptr m_impl; -}; - -} -} - -#endif diff --git a/beast/insight/CounterImpl.h b/beast/insight/CounterImpl.h deleted file mode 100644 index c970a0721b..0000000000 --- a/beast/insight/CounterImpl.h +++ /dev/null @@ -1,44 +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_INSIGHT_COUNTERIMPL_H_INCLUDED -#define BEAST_INSIGHT_COUNTERIMPL_H_INCLUDED - -#include - -namespace beast { -namespace insight { - -class Counter; - -class CounterImpl - : public std::enable_shared_from_this - , public BaseImpl -{ -public: - using value_type = std::int64_t; - - virtual ~CounterImpl () = 0; - virtual void increment (value_type amount) = 0; -}; - -} -} - -#endif diff --git a/beast/insight/Event.h b/beast/insight/Event.h deleted file mode 100644 index 73c65718ff..0000000000 --- a/beast/insight/Event.h +++ /dev/null @@ -1,85 +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_INSIGHT_EVENT_H_INCLUDED -#define BEAST_INSIGHT_EVENT_H_INCLUDED - -#include -#include - -#include - -#include -#include - -namespace beast { -namespace insight { - -/** A metric for reporting event timing. - - An event is an operation that has an associated millisecond time, or - other integral value. Because events happen at a specific moment, the - metric only supports a push-style interface. - - This is a lightweight reference wrapper which is cheap to copy and assign. - When the last reference goes away, the metric is no longer collected. -*/ -class Event : public Base -{ -public: - using value_type = EventImpl::value_type; - - /** Create a null metric. - A null metric reports no information. - */ - Event () - { } - - /** Create the metric reference the specified implementation. - Normally this won't be called directly. Instead, call the appropriate - factory function in the Collector interface. - @see Collector. - */ - explicit Event (std::shared_ptr const& impl) - : m_impl (impl) - { } - - /** Push an event notification. */ - template - void - notify (std::chrono::duration const& value) const - { - using namespace std::chrono; - if (m_impl) - m_impl->notify (ceil (value)); - } - - std::shared_ptr const& impl () const - { - return m_impl; - } - -private: - std::shared_ptr m_impl; -}; - -} -} - -#endif diff --git a/beast/insight/EventImpl.h b/beast/insight/EventImpl.h deleted file mode 100644 index 07f6d73890..0000000000 --- a/beast/insight/EventImpl.h +++ /dev/null @@ -1,44 +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_INSIGHT_EVENTIMPL_H_INCLUDED -#define BEAST_INSIGHT_EVENTIMPL_H_INCLUDED - -#include - -namespace beast { -namespace insight { - -class Event; - -class EventImpl - : public std::enable_shared_from_this - , public BaseImpl -{ -public: - using value_type = std::chrono::milliseconds; - - virtual ~EventImpl () = 0; - virtual void notify (value_type const& value) = 0; -}; - -} -} - -#endif diff --git a/beast/insight/Gauge.h b/beast/insight/Gauge.h deleted file mode 100644 index 60133ec5b1..0000000000 --- a/beast/insight/Gauge.h +++ /dev/null @@ -1,143 +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_INSIGHT_GAUGE_H_INCLUDED -#define BEAST_INSIGHT_GAUGE_H_INCLUDED - -#include -#include - -#include - -namespace beast { -namespace insight { - -/** A metric for measuring an integral value. - - A gauge is an instantaneous measurement of a value, like the gas gauge - in a car. The caller directly sets the value, or adjusts it by a - specified amount. The value is kept in the client rather than the collector. - - This is a lightweight reference wrapper which is cheap to copy and assign. - When the last reference goes away, the metric is no longer collected. -*/ -class Gauge : public Base -{ -public: - using value_type = GaugeImpl::value_type; - using difference_type = GaugeImpl::difference_type; - - /** Create a null metric. - A null metric reports no information. - */ - Gauge () - { - } - - /** Create the metric reference the specified implementation. - Normally this won't be called directly. Instead, call the appropriate - factory function in the Collector interface. - @see Collector. - */ - explicit Gauge (std::shared_ptr const& impl) - : m_impl (impl) - { - } - - /** Set the value on the gauge. - A Collector implementation should combine multiple calls to value - changes into a single change if the calls occur within a single - collection interval. - */ - /** @{ */ - void set (value_type value) const - { - if (m_impl) - m_impl->set (value); - } - - Gauge const& operator= (value_type value) const - { set (value); return *this; } - /** @} */ - - /** Adjust the value of the gauge. */ - /** @{ */ - void increment (difference_type amount) const - { - if (m_impl) - m_impl->increment (amount); - } - - Gauge const& - operator+= (difference_type amount) const - { - increment (amount); - return *this; - } - - Gauge const& - operator-= (difference_type amount) const - { - increment (-amount); - return *this; - } - - Gauge const& - operator++ () const - { - increment (1); - return *this; - } - - Gauge const& - operator++ (int) const - { - increment (1); - return *this; - } - - Gauge const& - operator-- () const - { - increment (-1); - return *this; - } - - Gauge const& - operator-- (int) const - { - increment (-1); - return *this; - } - /** @} */ - - std::shared_ptr const& - impl () const - { - return m_impl; - } - -private: - std::shared_ptr m_impl; -}; - -} -} - -#endif diff --git a/beast/insight/GaugeImpl.h b/beast/insight/GaugeImpl.h deleted file mode 100644 index 06703973f8..0000000000 --- a/beast/insight/GaugeImpl.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_INSIGHT_GAUGEIMPL_H_INCLUDED -#define BEAST_INSIGHT_GAUGEIMPL_H_INCLUDED - -#include - -namespace beast { -namespace insight { - -class Gauge; - -class GaugeImpl - : public std::enable_shared_from_this - , public BaseImpl -{ -public: - using value_type = std::uint64_t; - using difference_type = std::int64_t; - - virtual ~GaugeImpl () = 0; - virtual void set (value_type value) = 0; - virtual void increment (difference_type amount) = 0; -}; - -} -} - -#endif diff --git a/beast/insight/Group.h b/beast/insight/Group.h deleted file mode 100644 index e895403a96..0000000000 --- a/beast/insight/Group.h +++ /dev/null @@ -1,44 +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_INSIGHT_GROUP_H_INCLUDED -#define BEAST_INSIGHT_GROUP_H_INCLUDED - -#include - -#include -#include - -namespace beast { -namespace insight { - -/** A collector front-end that manages a group of metrics. */ -class Group : public Collector -{ -public: - using ptr = std::shared_ptr ; - - /** Returns the name of this group, for diagnostics. */ - virtual std::string const& name () const = 0; -}; - -} -} - -#endif diff --git a/beast/insight/Groups.h b/beast/insight/Groups.h deleted file mode 100644 index 4321869d82..0000000000 --- a/beast/insight/Groups.h +++ /dev/null @@ -1,58 +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_INSIGHT_GROUPS_H_INCLUDED -#define BEAST_INSIGHT_GROUPS_H_INCLUDED - -#include -#include - -#include -#include - -namespace beast { -namespace insight { - -/** A container for managing a set of metric groups. */ -class Groups -{ -public: - virtual ~Groups() = 0; - - /** Find or create a new collector with a given name. */ - /** @{ */ - virtual - Group::ptr const& - get (std::string const& name) = 0; - - Group::ptr const& - operator[] (std::string const& name) - { - return get (name); - } - /** @} */ -}; - -/** Create a group container that uses the specified collector. */ -std::unique_ptr make_Groups (Collector::ptr const& collector); - -} -} - -#endif diff --git a/beast/insight/Hook.h b/beast/insight/Hook.h deleted file mode 100644 index 31fbfe840e..0000000000 --- a/beast/insight/Hook.h +++ /dev/null @@ -1,62 +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_INSIGHT_HOOK_H_INCLUDED -#define BEAST_INSIGHT_HOOK_H_INCLUDED - -#include -#include - -#include - -namespace beast { -namespace insight { - -/** A reference to a handler for performing polled collection. */ -class Hook : public Base -{ -public: - /** Create a null hook. - A null hook has no associated handler. - */ - Hook () - { } - - /** Create a hook referencing the specified implementation. - Normally this won't be called directly. Instead, call the appropriate - factory function in the Collector interface. - @see Collector. - */ - explicit Hook (std::shared_ptr const& impl) - : m_impl (impl) - { } - - std::shared_ptr const& impl () const - { - return m_impl; - } - -private: - std::shared_ptr m_impl; -}; - -} -} - -#endif diff --git a/beast/insight/HookImpl.h b/beast/insight/HookImpl.h deleted file mode 100644 index 35ee91bc88..0000000000 --- a/beast/insight/HookImpl.h +++ /dev/null @@ -1,41 +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_INSIGHT_HOOKIMPL_H_INCLUDED -#define BEAST_INSIGHT_HOOKIMPL_H_INCLUDED - -#include - -namespace beast { -namespace insight { - -class HookImpl - : public std::enable_shared_from_this - , public BaseImpl -{ -public: - using HandlerType = std::function ; - - virtual ~HookImpl () = 0; -}; - -} -} - -#endif diff --git a/beast/insight/Insight.unity.cpp b/beast/insight/Insight.unity.cpp deleted file mode 100644 index 5439b2f7e9..0000000000 --- a/beast/insight/Insight.unity.cpp +++ /dev/null @@ -1,34 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include diff --git a/beast/insight/Meter.h b/beast/insight/Meter.h deleted file mode 100644 index a7325aa0b7..0000000000 --- a/beast/insight/Meter.h +++ /dev/null @@ -1,97 +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_INSIGHT_METER_H_INCLUDED -#define BEAST_INSIGHT_METER_H_INCLUDED - -#include - -#include -#include - -namespace beast { -namespace insight { - -/** A metric for measuring an integral value. - - A meter may be thought of as an increment-only counter. - - This is a lightweight reference wrapper which is cheap to copy and assign. - When the last reference goes away, the metric is no longer collected. -*/ -class Meter : public Base -{ -public: - using value_type = MeterImpl::value_type; - - /** Create a null metric. - A null metric reports no information. - */ - Meter () - { } - - /** Create the metric reference the specified implementation. - Normally this won't be called directly. Instead, call the appropriate - factory function in the Collector interface. - @see Collector. - */ - explicit Meter (std::shared_ptr const& impl) - : m_impl (impl) - { } - - /** Increment the meter. */ - /** @{ */ - void increment (value_type amount) const - { - if (m_impl) - m_impl->increment (amount); - } - - Meter const& operator+= (value_type amount) const - { - increment (amount); - return *this; - } - - Meter const& operator++ () const - { - increment (1); - return *this; - } - - Meter const& operator++ (int) const - { - increment (1); - return *this; - } - /** @} */ - - std::shared_ptr const& impl () const - { - return m_impl; - } - -private: - std::shared_ptr m_impl; -}; - -} -} - -#endif diff --git a/beast/insight/MeterImpl.h b/beast/insight/MeterImpl.h deleted file mode 100644 index defa546e08..0000000000 --- a/beast/insight/MeterImpl.h +++ /dev/null @@ -1,44 +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_INSIGHT_METERIMPL_H_INCLUDED -#define BEAST_INSIGHT_METERIMPL_H_INCLUDED - -#include - -namespace beast { -namespace insight { - -class Meter; - -class MeterImpl - : public std::enable_shared_from_this - , public BaseImpl -{ -public: - using value_type = std::uint64_t; - - virtual ~MeterImpl () = 0; - virtual void increment (value_type amount) = 0; -}; - -} -} - -#endif diff --git a/beast/insight/NullCollector.h b/beast/insight/NullCollector.h deleted file mode 100644 index 0656c94dde..0000000000 --- a/beast/insight/NullCollector.h +++ /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. -*/ -//============================================================================== - -#ifndef BEAST_INSIGHT_NULLCOLLECTOR_H_INCLUDED -#define BEAST_INSIGHT_NULLCOLLECTOR_H_INCLUDED - -#include - -namespace beast { -namespace insight { - -/** A Collector which does not collect metrics. */ -class NullCollector : public Collector -{ -public: - static std::shared_ptr New (); -}; - -} -} - -#endif diff --git a/beast/insight/StatsDCollector.h b/beast/insight/StatsDCollector.h deleted file mode 100644 index c078921ec8..0000000000 --- a/beast/insight/StatsDCollector.h +++ /dev/null @@ -1,52 +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_INSIGHT_STATSDCOLLECTOR_H_INCLUDED -#define BEAST_INSIGHT_STATSDCOLLECTOR_H_INCLUDED - -#include - -#include -#include - -namespace beast { -namespace insight { - -/** A Collector that reports metrics to a StatsD server. - Reference: - https://github.com/b/statsd_spec -*/ -class StatsDCollector : public Collector -{ -public: - /** Create a StatsD collector. - @param address The IP address and port of the StatsD server. - @param prefix A string pre-pended before each metric name. - @param journal Destination for logging output. - */ - static - std::shared_ptr - New (IP::Endpoint const& address, - std::string const& prefix, Journal journal); -}; - -} -} - -#endif diff --git a/beast/insight/impl/Collector.cpp b/beast/insight/impl/Collector.cpp deleted file mode 100644 index 2ab1d2fc57..0000000000 --- a/beast/insight/impl/Collector.cpp +++ /dev/null @@ -1,28 +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. -*/ -//============================================================================== - -namespace beast { -namespace insight { - -Collector::~Collector () -{ -} - -} -} diff --git a/beast/insight/impl/Group.cpp b/beast/insight/impl/Group.cpp deleted file mode 100644 index a80baa47b1..0000000000 --- a/beast/insight/impl/Group.cpp +++ /dev/null @@ -1,28 +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. -*/ -//============================================================================== - -namespace beast { -namespace insight { - -namespace detail { - -} - -} -} diff --git a/beast/insight/impl/Groups.cpp b/beast/insight/impl/Groups.cpp deleted file mode 100644 index c70c5b2009..0000000000 --- a/beast/insight/impl/Groups.cpp +++ /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. -*/ -//============================================================================== - -#include -#include -#include - -namespace beast { -namespace insight { - -namespace detail { - -class GroupImp - : public std::enable_shared_from_this - , public Group -{ -public: - using Items = std::vector >; - - std::string const m_name; - Collector::ptr m_collector; - - GroupImp (std::string const& name_, - Collector::ptr const& collector) - : m_name (name_) - , m_collector (collector) - { - } - - ~GroupImp () - { - } - - std::string const& name () const - { - return m_name; - } - - std::string make_name (std::string const& name) - { - return m_name + "." + name; - } - - Hook make_hook (HookImpl::HandlerType const& handler) - { - return m_collector->make_hook (handler); - } - - Counter make_counter (std::string const& name) - { - return m_collector->make_counter (make_name (name)); - } - - Event make_event (std::string const& name) - { - return m_collector->make_event (make_name (name)); - } - - Gauge make_gauge (std::string const& name) - { - return m_collector->make_gauge (make_name (name)); - } - - Meter make_meter (std::string const& name) - { - return m_collector->make_meter (make_name (name)); - } - -private: - GroupImp& operator= (GroupImp const&); -}; - -//------------------------------------------------------------------------------ - -class GroupsImp : public Groups -{ -public: - using Items = std::unordered_map , uhash <>>; - - Collector::ptr m_collector; - Items m_items; - - GroupsImp (Collector::ptr const& collector) - : m_collector (collector) - { - } - - ~GroupsImp () - { - } - - Group::ptr const& get (std::string const& name) - { - std::pair result ( - m_items.emplace (name, Group::ptr ())); - Group::ptr& group (result.first->second); - if (result.second) - group = std::make_shared (name, m_collector); - return group; - } -}; - -} - -//------------------------------------------------------------------------------ - -Groups::~Groups () -{ -} - -std::unique_ptr make_Groups (Collector::ptr const& collector) -{ - return std::make_unique (collector); -} - -} -} diff --git a/beast/insight/impl/Hook.cpp b/beast/insight/impl/Hook.cpp deleted file mode 100644 index e9392a59f6..0000000000 --- a/beast/insight/impl/Hook.cpp +++ /dev/null @@ -1,28 +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. -*/ -//============================================================================== - -namespace beast { -namespace insight { - -HookImpl::~HookImpl () -{ -} - -} -} diff --git a/beast/insight/impl/Metric.cpp b/beast/insight/impl/Metric.cpp deleted file mode 100644 index 22a7bd0496..0000000000 --- a/beast/insight/impl/Metric.cpp +++ /dev/null @@ -1,48 +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. -*/ -//============================================================================== - -namespace beast { -namespace insight { - -Base::~Base () -{ -} - -BaseImpl::~BaseImpl () -{ -} - -CounterImpl::~CounterImpl () -{ -} - -EventImpl::~EventImpl () -{ -} - -GaugeImpl::~GaugeImpl () -{ -} - -MeterImpl::~MeterImpl () -{ -} - -} -} diff --git a/beast/insight/impl/NullCollector.cpp b/beast/insight/impl/NullCollector.cpp deleted file mode 100644 index b9e407454e..0000000000 --- a/beast/insight/impl/NullCollector.cpp +++ /dev/null @@ -1,137 +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. -*/ -//============================================================================== - -namespace beast { -namespace insight { - -namespace detail { - -class NullHookImpl : public HookImpl -{ -private: - NullHookImpl& operator= (NullHookImpl const&); -}; - -//------------------------------------------------------------------------------ - -class NullCounterImpl : public CounterImpl -{ -public: - void increment (value_type) - { - } - -private: - NullCounterImpl& operator= (NullCounterImpl const&); -}; - -//------------------------------------------------------------------------------ - -class NullEventImpl : public EventImpl -{ -public: - void notify (value_type const&) - { - } - -private: - NullEventImpl& operator= (NullEventImpl const&); -}; - -//------------------------------------------------------------------------------ - -class NullGaugeImpl : public GaugeImpl -{ -public: - void set (value_type) - { - } - - void increment (difference_type) - { - } - -private: - NullGaugeImpl& operator= (NullGaugeImpl const&); -}; - -//------------------------------------------------------------------------------ - -class NullMeterImpl : public MeterImpl -{ -public: - void increment (value_type) - { - } - -private: - NullMeterImpl& operator= (NullMeterImpl const&); -}; - -//------------------------------------------------------------------------------ - -class NullCollectorImp : public NullCollector -{ -private: -public: - NullCollectorImp () - { - } - - ~NullCollectorImp () - { - } - - Hook make_hook (HookImpl::HandlerType const&) - { - return Hook (std::make_shared ()); - } - - Counter make_counter (std::string const&) - { - return Counter (std::make_shared ()); - } - - Event make_event (std::string const&) - { - return Event (std::make_shared ()); - } - - Gauge make_gauge (std::string const&) - { - return Gauge (std::make_shared ()); - } - - Meter make_meter (std::string const&) - { - return Meter (std::make_shared ()); - } -}; - -} - -//------------------------------------------------------------------------------ - -std::shared_ptr NullCollector::New () -{ - return std::make_shared (); -} - -} -} diff --git a/beast/insight/impl/StatsDCollector.cpp b/beast/insight/impl/StatsDCollector.cpp deleted file mode 100644 index 859f22e0fc..0000000000 --- a/beast/insight/impl/StatsDCollector.cpp +++ /dev/null @@ -1,712 +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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef BEAST_STATSDCOLLECTOR_TRACING_ENABLED -#define BEAST_STATSDCOLLECTOR_TRACING_ENABLED 0 -#endif - -namespace beast { -namespace insight { - -namespace detail { - -class StatsDCollectorImp; - -//------------------------------------------------------------------------------ - -class StatsDMetricBase : public List ::Node -{ -public: - virtual void do_process () = 0; -}; - -//------------------------------------------------------------------------------ - -class StatsDHookImpl - : public HookImpl - , public StatsDMetricBase -{ -public: - StatsDHookImpl ( - HandlerType const& handler, - std::shared_ptr const& impl); - - ~StatsDHookImpl (); - - void do_process (); - -private: - StatsDHookImpl& operator= (StatsDHookImpl const&); - - std::shared_ptr m_impl; - HandlerType m_handler; -}; - -//------------------------------------------------------------------------------ - -class StatsDCounterImpl - : public CounterImpl - , public StatsDMetricBase -{ -public: - StatsDCounterImpl (std::string const& name, - std::shared_ptr const& impl); - - ~StatsDCounterImpl (); - - void increment (CounterImpl::value_type amount); - - void flush (); - void do_increment (CounterImpl::value_type amount); - void do_process (); - -private: - StatsDCounterImpl& operator= (StatsDCounterImpl const&); - - std::shared_ptr m_impl; - std::string m_name; - CounterImpl::value_type m_value; - bool m_dirty; -}; - -//------------------------------------------------------------------------------ - -class StatsDEventImpl - : public EventImpl -{ -public: - StatsDEventImpl (std::string const& name, - std::shared_ptr const& impl); - - ~StatsDEventImpl (); - - void notify (EventImpl::value_type const& alue); - - void do_notify (EventImpl::value_type const& value); - void do_process (); - -private: - StatsDEventImpl& operator= (StatsDEventImpl const&); - - std::shared_ptr m_impl; - std::string m_name; -}; - -//------------------------------------------------------------------------------ - -class StatsDGaugeImpl - : public GaugeImpl - , public StatsDMetricBase -{ -public: - StatsDGaugeImpl (std::string const& name, - std::shared_ptr const& impl); - - ~StatsDGaugeImpl (); - - void set (GaugeImpl::value_type value); - void increment (GaugeImpl::difference_type amount); - - void flush (); - void do_set (GaugeImpl::value_type value); - void do_increment (GaugeImpl::difference_type amount); - void do_process (); - -private: - StatsDGaugeImpl& operator= (StatsDGaugeImpl const&); - - std::shared_ptr m_impl; - std::string m_name; - GaugeImpl::value_type m_last_value; - GaugeImpl::value_type m_value; - bool m_dirty; -}; - -//------------------------------------------------------------------------------ - -class StatsDMeterImpl - : public MeterImpl - , public StatsDMetricBase -{ -public: - explicit StatsDMeterImpl (std::string const& name, - std::shared_ptr const& impl); - - ~StatsDMeterImpl (); - - void increment (MeterImpl::value_type amount); - - void flush (); - void do_increment (MeterImpl::value_type amount); - void do_process (); - -private: - StatsDMeterImpl& operator= (StatsDMeterImpl const&); - - std::shared_ptr m_impl; - std::string m_name; - MeterImpl::value_type m_value; - bool m_dirty; -}; - -//------------------------------------------------------------------------------ - -class StatsDCollectorImp - : public StatsDCollector - , public std::enable_shared_from_this -{ -private: - enum - { - //max_packet_size = 484 - max_packet_size = 1472 - }; - - Journal m_journal; - IP::Endpoint m_address; - std::string m_prefix; - boost::asio::io_service m_io_service; - boost::optional m_work; - boost::asio::io_service::strand m_strand; - boost::asio::deadline_timer m_timer; - boost::asio::ip::udp::socket m_socket; - std::deque m_data; - std::recursive_mutex metricsLock_; - List metrics_; - - // Must come last for order of init - std::thread m_thread; - - static boost::asio::ip::udp::endpoint to_endpoint ( - IP::Endpoint const &address) - { - if (address.is_v4 ()) - { - return boost::asio::ip::udp::endpoint ( - boost::asio::ip::address_v4 ( - address.to_v4().value), address.port ()); - } - - // VFALCO TODO IPv6 support - assert(false); - return boost::asio::ip::udp::endpoint ( - boost::asio::ip::address_v6 (), 0); - } - -public: - StatsDCollectorImp ( - IP::Endpoint const& address, - std::string const& prefix, - Journal journal) - : m_journal (journal) - , m_address (address) - , m_prefix (prefix) - , m_work (std::ref (m_io_service)) - , m_strand (m_io_service) - , m_timer (m_io_service) - , m_socket (m_io_service) - , m_thread (&StatsDCollectorImp::run, this) - { - } - - ~StatsDCollectorImp () - { - boost::system::error_code ec; - m_timer.cancel (ec); - - m_work = boost::none; - m_thread.join (); - } - - Hook make_hook (HookImpl::HandlerType const& handler) - { - return Hook (std::make_shared ( - handler, shared_from_this ())); - } - - Counter make_counter (std::string const& name) - { - return Counter (std::make_shared ( - name, shared_from_this ())); - } - - Event make_event (std::string const& name) - { - return Event (std::make_shared ( - name, shared_from_this ())); - } - - Gauge make_gauge (std::string const& name) - { - return Gauge (std::make_shared ( - name, shared_from_this ())); - } - - Meter make_meter (std::string const& name) - { - return Meter (std::make_shared ( - name, shared_from_this ())); - } - - //-------------------------------------------------------------------------- - - void add (StatsDMetricBase& metric) - { - std::lock_guard _(metricsLock_); - metrics_.push_back (metric); - } - - void remove (StatsDMetricBase& metric) - { - std::lock_guard _(metricsLock_); - metrics_.erase (metrics_.iterator_to (metric)); - } - - //-------------------------------------------------------------------------- - - boost::asio::io_service& get_io_service () - { - return m_io_service; - } - - std::string const& prefix () const - { - return m_prefix; - } - - void do_post_buffer (std::string const& buffer) - { - m_data.emplace_back (buffer); - } - - void post_buffer (std::string&& buffer) - { - m_io_service.dispatch (m_strand.wrap (std::bind ( - &StatsDCollectorImp::do_post_buffer, this, - std::move (buffer)))); - } - - // The keepAlive parameter makes sure the buffers sent to - // boost::asio::async_send do not go away until the call is finished - void on_send (std::shared_ptr> /*keepAlive*/, - boost::system::error_code ec, std::size_t) - { - if (ec == boost::asio::error::operation_aborted) - return; - - if (ec) - { - if (auto stream = m_journal.error()) - stream << "async_send failed: " << ec.message(); - return; - } - } - - void log (std::vector const& buffers) - { - (void)buffers; -#if BEAST_STATSDCOLLECTOR_TRACING_ENABLED - std::stringstream ss; - for (auto const& buffer : buffers) - { - std::string const s (boost::asio::buffer_cast (buffer), - boost::asio::buffer_size (buffer)); - ss << s; - } - //m_journal.trace << std::endl << ss.str (); - outputDebugString (ss.str ()); -#endif - } - - // Send what we have - void send_buffers () - { - if (m_data.empty ()) - return; - - // Break up the array of strings into blocks - // that each fit into one UDP packet. - // - boost::system::error_code ec; - std::vector buffers; - buffers.reserve (m_data.size ()); - std::size_t size (0); - - auto keepAlive = - std::make_shared>(std::move (m_data)); - m_data.clear (); - - for (auto const& s : *keepAlive) - { - std::size_t const length (s.size ()); - assert (! s.empty ()); - if (! buffers.empty () && (size + length) > max_packet_size) - { -#if BEAST_STATSDCOLLECTOR_TRACING_ENABLED - log (buffers); -#endif - m_socket.async_send (buffers, std::bind ( - &StatsDCollectorImp::on_send, this, keepAlive, - beast::asio::placeholders::error, - beast::asio::placeholders::bytes_transferred)); - buffers.clear (); - size = 0; - } - - buffers.emplace_back (&s[0], length); - size += length; - } - - if (! buffers.empty ()) - { -#if BEAST_STATSDCOLLECTOR_TRACING_ENABLED - log (buffers); -#endif - m_socket.async_send (buffers, std::bind ( - &StatsDCollectorImp::on_send, this, keepAlive, - beast::asio::placeholders::error, - beast::asio::placeholders::bytes_transferred)); - } - } - - void set_timer () - { - m_timer.expires_from_now (boost::posix_time::seconds (1)); - m_timer.async_wait (std::bind ( - &StatsDCollectorImp::on_timer, this, - beast::asio::placeholders::error)); - } - - void on_timer (boost::system::error_code ec) - { - if (ec == boost::asio::error::operation_aborted) - return; - - if (ec) - { - if (auto stream = m_journal.error()) - stream << "on_timer failed: " << ec.message(); - return; - } - - std::lock_guard _(metricsLock_); - - for (auto& m : metrics_) - m.do_process(); - - send_buffers (); - - set_timer (); - } - - void run () - { - boost::system::error_code ec; - - if (m_socket.connect (to_endpoint (m_address), ec)) - { - if (auto stream = m_journal.error()) - stream << "Connect failed: " << ec.message(); - return; - } - - set_timer (); - - m_io_service.run (); - - m_socket.shutdown ( - boost::asio::ip::udp::socket::shutdown_send, ec); - - m_socket.close (); - - m_io_service.poll (); - } -}; - -//------------------------------------------------------------------------------ - -StatsDHookImpl::StatsDHookImpl (HandlerType const& handler, - std::shared_ptr const& impl) - : m_impl (impl) - , m_handler (handler) -{ - m_impl->add (*this); -} - -StatsDHookImpl::~StatsDHookImpl () -{ - m_impl->remove (*this); -} - -void StatsDHookImpl::do_process () -{ - m_handler (); -} - -//------------------------------------------------------------------------------ - -StatsDCounterImpl::StatsDCounterImpl (std::string const& name, - std::shared_ptr const& impl) - : m_impl (impl) - , m_name (name) - , m_value (0) - , m_dirty (false) -{ - m_impl->add (*this); -} - -StatsDCounterImpl::~StatsDCounterImpl () -{ - m_impl->remove (*this); -} - -void StatsDCounterImpl::increment (CounterImpl::value_type amount) -{ - m_impl->get_io_service().dispatch (std::bind ( - &StatsDCounterImpl::do_increment, - std::static_pointer_cast ( - shared_from_this ()), amount)); -} - -void StatsDCounterImpl::flush () -{ - if (m_dirty) - { - m_dirty = false; - std::stringstream ss; - ss << - m_impl->prefix() << "." << - m_name << ":" << - m_value << "|c" << - "\n"; - m_value = 0; - m_impl->post_buffer (ss.str ()); - } -} - -void StatsDCounterImpl::do_increment (CounterImpl::value_type amount) -{ - m_value += amount; - m_dirty = true; -} - -void StatsDCounterImpl::do_process () -{ - flush (); -} - -//------------------------------------------------------------------------------ - -StatsDEventImpl::StatsDEventImpl (std::string const& name, - std::shared_ptr const& impl) - : m_impl (impl) - , m_name (name) -{ -} - -StatsDEventImpl::~StatsDEventImpl () -{ -} - -void StatsDEventImpl::notify (EventImpl::value_type const& value) -{ - 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 const& value) -{ - std::stringstream ss; - ss << - m_impl->prefix() << "." << - m_name << ":" << - value.count() << "|ms" << - "\n"; - m_impl->post_buffer (ss.str ()); -} - -//------------------------------------------------------------------------------ - -StatsDGaugeImpl::StatsDGaugeImpl (std::string const& name, - std::shared_ptr const& impl) - : m_impl (impl) - , m_name (name) - , m_last_value (0) - , m_value (0) - , m_dirty (false) -{ - m_impl->add (*this); -} - -StatsDGaugeImpl::~StatsDGaugeImpl () -{ - m_impl->remove (*this); -} - -void StatsDGaugeImpl::set (GaugeImpl::value_type value) -{ - 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 (std::bind ( - &StatsDGaugeImpl::do_increment, - std::static_pointer_cast ( - shared_from_this ()), amount)); -} - -void StatsDGaugeImpl::flush () -{ - if (m_dirty) - { - m_dirty = false; - std::stringstream ss; - ss << - m_impl->prefix() << "." << - m_name << ":" << - m_value << "|c" << - "\n"; - m_impl->post_buffer (ss.str ()); - } -} - -void StatsDGaugeImpl::do_set (GaugeImpl::value_type value) -{ - m_value = value; - - if (m_value != m_last_value) - { - m_last_value = m_value; - m_dirty = true; - } -} - -void StatsDGaugeImpl::do_increment (GaugeImpl::difference_type amount) -{ - GaugeImpl::value_type value (m_value); - - if (amount > 0) - { - GaugeImpl::value_type const d ( - static_cast (amount)); - value += - (d >= std::numeric_limits ::max() - m_value) - ? std::numeric_limits ::max() - m_value - : d; - } - else if (amount < 0) - { - GaugeImpl::value_type const d ( - static_cast (-amount)); - value = (d >= value) ? 0 : value - d; - } - - do_set (value); -} - -void StatsDGaugeImpl::do_process () -{ - flush (); -} - -//------------------------------------------------------------------------------ - -StatsDMeterImpl::StatsDMeterImpl (std::string const& name, - std::shared_ptr const& impl) - : m_impl (impl) - , m_name (name) - , m_value (0) - , m_dirty (false) -{ - m_impl->add (*this); -} - -StatsDMeterImpl::~StatsDMeterImpl () -{ - m_impl->remove (*this); -} - -void StatsDMeterImpl::increment (MeterImpl::value_type amount) -{ - m_impl->get_io_service().dispatch (std::bind ( - &StatsDMeterImpl::do_increment, - std::static_pointer_cast ( - shared_from_this ()), amount)); -} - -void StatsDMeterImpl::flush () -{ - if (m_dirty) - { - m_dirty = false; - std::stringstream ss; - ss << - m_impl->prefix() << "." << - m_name << ":" << - m_value << "|m" << - "\n"; - m_value = 0; - m_impl->post_buffer (ss.str ()); - } -} - -void StatsDMeterImpl::do_increment (MeterImpl::value_type amount) -{ - m_value += amount; - m_dirty = true; -} - -void StatsDMeterImpl::do_process () -{ - flush (); -} - -} - -//------------------------------------------------------------------------------ - -std::shared_ptr StatsDCollector::New ( - IP::Endpoint const& address, std::string const& prefix, Journal journal) -{ - return std::make_shared ( - address, prefix, journal); -} - -} -} diff --git a/beast/intrusive/List.h b/beast/intrusive/List.h deleted file mode 100644 index f0bfbe8760..0000000000 --- a/beast/intrusive/List.h +++ /dev/null @@ -1,559 +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_LIST_H_INCLUDED -#define BEAST_INTRUSIVE_LIST_H_INCLUDED - -#include - -#include -#include - -namespace beast { - -template -class List; - -namespace detail { - -/** Copy `const` attribute from T to U if present. */ -/** @{ */ -template -struct CopyConst -{ - using type = typename std::remove_const ::type; -}; - -template -struct CopyConst -{ - using type = typename std::remove_const ::type const; -}; -/** @} */ - -// This is the intrusive portion of the doubly linked list. -// One derivation per list that the object may appear on -// concurrently is required. -// -template -class ListNode -{ -private: - using value_type = T; - - friend class List; - - template - friend class ListIterator; - - ListNode* m_next; - ListNode* m_prev; -}; - -//------------------------------------------------------------------------------ - -template -class ListIterator : public std::iterator < - std::bidirectional_iterator_tag, std::size_t> -{ -public: - using value_type = typename detail::CopyConst < - N, typename N::value_type>::type; - using pointer = value_type*; - using reference = value_type&; - using size_type = std::size_t; - - ListIterator (N* node = nullptr) noexcept - : m_node (node) - { - } - - template - ListIterator (ListIterator const& other) noexcept - : m_node (other.m_node) - { - } - - template - bool operator== (ListIterator const& other) const noexcept - { - return m_node == other.m_node; - } - - template - bool operator!= (ListIterator const& other) const noexcept - { - return ! ((*this) == other); - } - - reference operator* () const noexcept - { - return dereference (); - } - - pointer operator-> () const noexcept - { - return &dereference (); - } - - ListIterator& operator++ () noexcept - { - increment (); - return *this; - } - - ListIterator operator++ (int) noexcept - { - ListIterator result (*this); - increment (); - return result; - } - - ListIterator& operator-- () noexcept - { - decrement (); - return *this; - } - - ListIterator operator-- (int) noexcept - { - ListIterator result (*this); - decrement (); - return result; - } - -private: - reference dereference () const noexcept - { - return static_cast (*m_node); - } - - void increment () noexcept - { - m_node = m_node->m_next; - } - - void decrement () noexcept - { - m_node = m_node->m_prev; - } - - N* m_node; -}; - -} - -/** Intrusive doubly linked list. - - This intrusive List is a container similar in operation to std::list in the - Standard Template Library (STL). Like all @ref intrusive containers, List - requires you to first derive your class from List<>::Node: - - @code - - struct Object : List ::Node - { - explicit Object (int value) : m_value (value) - { - } - - int m_value; - }; - - @endcode - - Now we define the list, and add a couple of items. - - @code - - List list; - - list.push_back (* (new Object (1))); - list.push_back (* (new Object (2))); - - @endcode - - For compatibility with the standard containers, push_back() expects a - reference to the object. Unlike the standard container, however, push_back() - places the actual object in the list and not a copy-constructed duplicate. - - Iterating over the list follows the same idiom as the STL: - - @code - - for (List ::iterator iter = list.begin(); iter != list.end; ++iter) - std::cout << iter->m_value; - - @endcode - - You can even use BOOST_FOREACH, or range based for loops: - - @code - - BOOST_FOREACH (Object& object, list) // boost only - std::cout << object.m_value; - - for (Object& object : list) // C++11 only - std::cout << object.m_value; - - @endcode - - Because List is mostly STL compliant, it can be passed into STL algorithms: - e.g. `std::for_each()` or `std::find_first_of()`. - - In general, objects placed into a List should be dynamically allocated - although this cannot be enforced at compile time. Since the caller provides - the storage for the object, the caller is also responsible for deleting the - object. An object still exists after being removed from a List, until the - caller deletes it. This means an element can be moved from one List to - another with practically no overhead. - - Unlike the standard containers, an object may only exist in one list at a - time, unless special preparations are made. The Tag template parameter is - used to distinguish between different list types for the same object, - allowing the object to exist in more than one list simultaneously. - - For example, consider an actor system where a global list of actors is - maintained, so that they can each be periodically receive processing - time. We wish to also maintain a list of the subset of actors that require - a domain-dependent update. To achieve this, we declare two tags, the - associated list types, and the list element thusly: - - @code - - struct Actor; // Forward declaration required - - struct ProcessTag { }; - struct UpdateTag { }; - - using ProcessList = List ; - using UpdateList = List ; - - // Derive from both node types so we can be in each list at once. - // - struct Actor : ProcessList::Node, UpdateList::Node - { - bool process (); // returns true if we need an update - void update (); - }; - - @endcode - - @tparam T The base type of element which the list will store - pointers to. - - @tparam Tag An optional unique type name used to distinguish lists and nodes, - when the object can exist in multiple lists simultaneously. - - @ingroup beast_core intrusive -*/ -template -class List -{ -public: - using Node = typename detail::ListNode ; - - using value_type = T; - using pointer = value_type*; - using reference = value_type&; - using const_pointer = value_type const*; - using const_reference = value_type const&; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - - using iterator = detail::ListIterator ; - using const_iterator = detail::ListIterator ; - - /** Create an empty list. */ - List () - { - m_head.m_prev = nullptr; // identifies the head - m_tail.m_next = nullptr; // identifies the tail - clear (); - } - - List(List const&) = delete; - List& operator= (List const&) = delete; - - /** Determine if the list is empty. - @return `true` if the list is empty. - */ - bool empty () const noexcept - { - return size () == 0; - } - - /** Returns the number of elements in the list. */ - size_type size () const noexcept - { - return m_size; - } - - /** Obtain a reference to the first element. - @invariant The list may not be empty. - @return A reference to the first element. - */ - reference front () noexcept - { - return element_from (m_head.m_next); - } - - /** Obtain a const reference to the first element. - @invariant The list may not be empty. - @return A const reference to the first element. - */ - const_reference front () const noexcept - { - return element_from (m_head.m_next); - } - - /** Obtain a reference to the last element. - @invariant The list may not be empty. - @return A reference to the last element. - */ - reference back () noexcept - { - return element_from (m_tail.m_prev); - } - - /** Obtain a const reference to the last element. - @invariant The list may not be empty. - @return A const reference to the last element. - */ - const_reference back () const noexcept - { - return element_from (m_tail.m_prev); - } - - /** Obtain an iterator to the beginning of the list. - @return An iterator pointing to the beginning of the list. - */ - iterator begin () noexcept - { - return iterator (m_head.m_next); - } - - /** Obtain a const iterator to the beginning of the list. - @return A const iterator pointing to the beginning of the list. - */ - const_iterator begin () const noexcept - { - return const_iterator (m_head.m_next); - } - - /** Obtain a const iterator to the beginning of the list. - @return A const iterator pointing to the beginning of the list. - */ - const_iterator cbegin () const noexcept - { - return const_iterator (m_head.m_next); - } - - /** Obtain a iterator to the end of the list. - @return An iterator pointing to the end of the list. - */ - iterator end () noexcept - { - return iterator (&m_tail); - } - - /** Obtain a const iterator to the end of the list. - @return A constiterator pointing to the end of the list. - */ - const_iterator end () const noexcept - { - return const_iterator (&m_tail); - } - - /** Obtain a const iterator to the end of the list - @return A constiterator pointing to the end of the list. - */ - const_iterator cend () const noexcept - { - return const_iterator (&m_tail); - } - - /** Clear the list. - @note This does not free the elements. - */ - void clear () noexcept - { - m_head.m_next = &m_tail; - m_tail.m_prev = &m_head; - m_size = 0; - } - - /** Insert an element. - @invariant The element must not already be in the list. - @param pos The location to insert after. - @param element The element to insert. - @return An iterator pointing to the newly inserted element. - */ - iterator insert (iterator pos, T& element) noexcept - { - Node* node = static_cast (&element); - node->m_next = &*pos; - node->m_prev = node->m_next->m_prev; - node->m_next->m_prev = node; - node->m_prev->m_next = node; - ++m_size; - return iterator (node); - } - - /** Insert another list into this one. - The other list is cleared. - @param pos The location to insert after. - @param other The list to insert. - */ - void insert (iterator pos, List& other) noexcept - { - if (!other.empty ()) - { - Node* before = &*pos; - other.m_head.m_next->m_prev = before->m_prev; - before->m_prev->m_next = other.m_head.m_next; - other.m_tail.m_prev->m_next = before; - before->m_prev = other.m_tail.m_prev; - m_size += other.m_size; - other.clear (); - } - } - - /** Remove an element. - @invariant The element must exist in the list. - @param pos An iterator pointing to the element to remove. - @return An iterator pointing to the next element after the one removed. - */ - iterator erase (iterator pos) noexcept - { - Node* node = &*pos; - ++pos; - node->m_next->m_prev = node->m_prev; - node->m_prev->m_next = node->m_next; - --m_size; - return pos; - } - - /** Insert an element at the beginning of the list. - @invariant The element must not exist in the list. - @param element The element to insert. - */ - iterator push_front (T& element) noexcept - { - return insert (begin (), element); - } - - /** Remove the element at the beginning of the list. - @invariant The list must not be empty. - @return A reference to the popped element. - */ - T& pop_front () noexcept - { - T& element (front ()); - erase (begin ()); - return element; - } - - /** Append an element at the end of the list. - @invariant The element must not exist in the list. - @param element The element to append. - */ - iterator push_back (T& element) noexcept - { - return insert (end (), element); - } - - /** Remove the element at the end of the list. - @invariant The list must not be empty. - @return A reference to the popped element. - */ - T& pop_back () noexcept - { - T& element (back ()); - erase (--end ()); - return element; - } - - /** Swap contents with another list. */ - void swap (List& other) noexcept - { - List temp; - temp.append (other); - other.append (*this); - append (temp); - } - - /** Insert another list at the beginning of this list. - The other list is cleared. - @param list The other list to insert. - */ - iterator prepend (List& list) noexcept - { - return insert (begin (), list); - } - - /** Append another list at the end of this list. - The other list is cleared. - @param list the other list to append. - */ - iterator append (List& list) noexcept - { - return insert (end (), list); - } - - /** Obtain an iterator from an element. - @invariant The element must exist in the list. - @param element The element to obtain an iterator for. - @return An iterator to the element. - */ - iterator iterator_to (T& element) const noexcept - { - return iterator (static_cast (&element)); - } - - /** Obtain a const iterator from an element. - @invariant The element must exist in the list. - @param element The element to obtain an iterator for. - @return A const iterator to the element. - */ - const_iterator const_iterator_to (T const& element) const noexcept - { - return const_iterator (static_cast (&element)); - } - -private: - reference element_from (Node* node) noexcept - { - return *(static_cast (node)); - } - - const_reference element_from (Node const* node) const noexcept - { - return *(static_cast (node)); - } - -private: - size_type m_size; - Node m_head; - Node m_tail; -}; - -} - -#endif diff --git a/beast/intrusive/LockFreeStack.h b/beast/intrusive/LockFreeStack.h deleted file mode 100644 index eae0d11908..0000000000 --- a/beast/intrusive/LockFreeStack.h +++ /dev/null @@ -1,294 +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_LOCKFREESTACK_H_INCLUDED -#define BEAST_INTRUSIVE_LOCKFREESTACK_H_INCLUDED - -#include -#include -#include - -namespace beast { - -//------------------------------------------------------------------------------ - -template -class LockFreeStackIterator - : public std::iterator < - std::forward_iterator_tag, - typename Container::value_type, - typename Container::difference_type, - typename std::conditional ::type, - typename std::conditional ::type> -{ -protected: - using Node = typename Container::Node; - using NodePtr = typename std::conditional < - IsConst, Node const*, Node*>::type; - -public: - using value_type = typename Container::value_type; - using pointer = typename std::conditional ::type; - using reference = typename std::conditional ::type; - - LockFreeStackIterator () - : m_node () - { - } - - LockFreeStackIterator (NodePtr node) - : m_node (node) - { - } - - template - explicit LockFreeStackIterator (LockFreeStackIterator const& other) - : m_node (other.m_node) - { - } - - LockFreeStackIterator& operator= (NodePtr node) - { - m_node = node; - return static_cast (*this); - } - - LockFreeStackIterator& operator++ () - { - m_node = m_node->m_next.load (); - return static_cast (*this); - } - - LockFreeStackIterator operator++ (int) - { - LockFreeStackIterator result (*this); - m_node = m_node->m_next; - return result; - } - - NodePtr node() const - { - return m_node; - } - - reference operator* () const - { - return *this->operator-> (); - } - - pointer operator-> () const - { - return static_cast (m_node); - } - -private: - NodePtr m_node; -}; - -//------------------------------------------------------------------------------ - -template -bool operator== (LockFreeStackIterator const& lhs, - LockFreeStackIterator const& rhs) -{ - return lhs.node() == rhs.node(); -} - -template -bool operator!= (LockFreeStackIterator const& lhs, - LockFreeStackIterator const& rhs) -{ - return lhs.node() != rhs.node(); -} - -//------------------------------------------------------------------------------ - -/** Multiple Producer, Multiple Consumer (MPMC) intrusive stack. - - This stack is implemented using the same intrusive interface as List. - All mutations are lock-free. - - The caller is responsible for preventing the "ABA" problem: - http://en.wikipedia.org/wiki/ABA_problem - - @param Tag A type name used to distinguish lists and nodes, for - putting objects in multiple lists. If this parameter is - omitted, the default tag is used. -*/ -template -class LockFreeStack -{ -public: - class Node - { - public: - Node () - : m_next (nullptr) - { } - - explicit Node (Node* next) - : m_next (next) - { } - - Node(Node const&) = delete; - Node& operator= (Node const&) = delete; - - private: - friend class LockFreeStack; - - template - friend class LockFreeStackIterator; - - std::atomic m_next; - }; - -public: - using value_type = Element; - using pointer = Element*; - using reference = Element&; - using const_pointer = Element const*; - using const_reference = Element const&; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - using iterator = LockFreeStackIterator < - LockFreeStack , false>; - using const_iterator = LockFreeStackIterator < - LockFreeStack , true>; - - LockFreeStack () - : m_end (nullptr) - , m_head (&m_end) - { - } - - LockFreeStack(LockFreeStack const&) = delete; - LockFreeStack& operator= (LockFreeStack const&) = delete; - - /** Returns true if the stack is empty. */ - bool empty() const - { - return m_head.load () == &m_end; - } - - /** Push a node onto the stack. - The caller is responsible for preventing the ABA problem. - This operation is lock-free. - Thread safety: - Safe to call from any thread. - - @param node The node to push. - - @return `true` if the stack was previously empty. If multiple threads - are attempting to push, only one will receive `true`. - */ - // VFALCO NOTE Fix this, shouldn't it be a reference like intrusive list? - bool push_front (Node* node) - { - bool first; - Node* old_head = m_head.load (std::memory_order_relaxed); - do - { - first = (old_head == &m_end); - node->m_next = old_head; - } - while (!m_head.compare_exchange_strong (old_head, node, - std::memory_order_release, - std::memory_order_relaxed)); - return first; - } - - /** Pop an element off the stack. - The caller is responsible for preventing the ABA problem. - This operation is lock-free. - Thread safety: - Safe to call from any thread. - - @return The element that was popped, or `nullptr` if the stack - was empty. - */ - Element* pop_front () - { - Node* node = m_head.load (); - Node* new_head; - do - { - if (node == &m_end) - return nullptr; - new_head = node->m_next.load (); - } - while (!m_head.compare_exchange_strong (node, new_head, - std::memory_order_release, - std::memory_order_relaxed)); - return static_cast (node); - } - - /** Return a forward iterator to the beginning or end of the stack. - Undefined behavior results if push_front or pop_front is called - while an iteration is in progress. - Thread safety: - Caller is responsible for synchronization. - */ - /** @{ */ - iterator begin () - { - return iterator (m_head.load ()); - } - - iterator end () - { - return iterator (&m_end); - } - - const_iterator begin () const - { - return const_iterator (m_head.load ()); - } - - const_iterator end () const - { - return const_iterator (&m_end); - } - - const_iterator cbegin () const - { - return const_iterator (m_head.load ()); - } - - const_iterator cend () const - { - return const_iterator (&m_end); - } - /** @} */ - -private: - Node m_end; - std::atomic m_head; -}; - -} - -#endif diff --git a/beast/module/README.md b/beast/module/README.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/beast/module/asio/AsyncObject.h b/beast/module/asio/AsyncObject.h deleted file mode 100644 index 38c6cc03f5..0000000000 --- a/beast/module/asio/AsyncObject.h +++ /dev/null @@ -1,98 +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_MODULE_ASIO_ASYNCOBJECT_H_INCLUDED -#define BEAST_MODULE_ASIO_ASYNCOBJECT_H_INCLUDED - -#include -#include - -namespace beast { -namespace asio { - -/** Mix-in to track when all pending I/O is complete. - Derived classes must be callable with this signature: - void asyncHandlersComplete() -*/ -template -class AsyncObject -{ -protected: - AsyncObject () - : m_pending (0) - { } - -public: - ~AsyncObject () - { - // Destroying the object with I/O pending? Not a clean exit! - assert (m_pending.load () == 0); - } - - /** RAII container that maintains the count of pending I/O. - Bind this into the argument list of every handler passed - to an initiating function. - */ - class CompletionCounter - { - public: - explicit CompletionCounter (Derived* owner) - : m_owner (owner) - { - ++m_owner->m_pending; - } - - CompletionCounter (CompletionCounter const& other) - : m_owner (other.m_owner) - { - ++m_owner->m_pending; - } - - ~CompletionCounter () - { - if (--m_owner->m_pending == 0) - m_owner->asyncHandlersComplete (); - } - - CompletionCounter& operator= (CompletionCounter const&) = delete; - - private: - Derived* m_owner; - }; - - void addReference () - { - ++m_pending; - } - - void removeReference () - { - if (--m_pending == 0) - (static_cast(this))->asyncHandlersComplete(); - } - -private: - // The number of handlers pending. - std::atomic m_pending; -}; - -} -} - -#endif diff --git a/beast/module/core/core.h b/beast/module/core/core.h deleted file mode 100644 index bb8782e01b..0000000000 --- a/beast/module/core/core.h +++ /dev/null @@ -1,78 +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_MODULE_CORE_CORE_H_INCLUDED -#define BEAST_MODULE_CORE_CORE_H_INCLUDED - -// TargetPlatform.h should not use anything from BeastConfig.h -#include - -#if BEAST_MSVC -# pragma warning (disable: 4251) // (DLL build warning, must be disabled before pushing the warning state) -# pragma warning (push) -# pragma warning (disable: 4786) // (long class name warning) -# ifdef __INTEL_COMPILER -# pragma warning (disable: 1125) -# endif -#endif - -//------------------------------------------------------------------------------ - -// New header-only library modeled more closely according to boost -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include - -// Order matters, since headers don't have their own #include lines. -// Add new includes to the bottom. - -#include - -#include -#include -#include - -#include -#include -#include - -#include - -#include - -#include - -#if BEAST_MSVC -#pragma warning (pop) -#endif - -#endif diff --git a/beast/module/core/core.unity.cpp b/beast/module/core/core.unity.cpp deleted file mode 100644 index 188b5773d6..0000000000 --- a/beast/module/core/core.unity.cpp +++ /dev/null @@ -1,188 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -//============================================================================== - -#include -#include - -#include -#include - -#if ! BEAST_BSD - #include -#endif - -#if ! BEAST_ANDROID - #include -#endif - -#if BEAST_WINDOWS - #include - #include - #include - - #if ! BEAST_MINGW - #pragma warning ( push ) - #pragma warning ( disable: 4091 ) - #include - #pragma warning ( pop ) - - #if ! BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES - #pragma comment (lib, "DbgHelp.lib") - #endif - #endif - - #if BEAST_MINGW - #include - #endif - -#else - #if BEAST_LINUX || BEAST_ANDROID - #include - #include - #include - #include - #include - #endif - - #if BEAST_LINUX - #include - #endif - - #include - #include - #include - #include - #include - #include - #include - #include - - #if ! BEAST_ANDROID && ! BEAST_BSD - #include - #endif -#endif - -#if BEAST_MAC || BEAST_IOS - #include - #include -#endif - -#if BEAST_ANDROID - #include -#endif - -//------------------------------------------------------------------------------ - -// If the MSVC debug heap headers were included, disable -// the macros during the juce include since they conflict. -#ifdef _CRTDBG_MAP_ALLOC -#pragma push_macro("calloc") -#pragma push_macro("free") -#pragma push_macro("malloc") -#pragma push_macro("realloc") -#pragma push_macro("_recalloc") -#pragma push_macro("_aligned_free") -#pragma push_macro("_aligned_malloc") -#pragma push_macro("_aligned_offset_malloc") -#pragma push_macro("_aligned_realloc") -#pragma push_macro("_aligned_recalloc") -#pragma push_macro("_aligned_offset_realloc") -#pragma push_macro("_aligned_offset_recalloc") -#pragma push_macro("_aligned_msize") -#undef calloc -#undef free -#undef malloc -#undef realloc -#undef _recalloc -#undef _aligned_free -#undef _aligned_malloc -#undef _aligned_offset_malloc -#undef _aligned_realloc -#undef _aligned_recalloc -#undef _aligned_offset_realloc -#undef _aligned_offset_recalloc -#undef _aligned_msize -#endif - -#include -#include -#include - -#include - -#include - -#include -#include - -#include - -#if BEAST_MAC || BEAST_IOS -#include -#endif - -#if BEAST_ANDROID -#include "native/android_JNIHelpers.h" -#endif - -#if BEAST_MAC || BEAST_IOS -#include - -#elif BEAST_WINDOWS -#include - -#elif BEAST_LINUX -#include - -#elif BEAST_BSD -#include - -#elif BEAST_ANDROID -#include "native/android_Files.cpp" -#include "native/android_Misc.cpp" -#include "native/android_SystemStats.cpp" -#include "native/android_Threads.cpp" - -#endif - -#ifdef _CRTDBG_MAP_ALLOC -#pragma pop_macro("calloc") -#pragma pop_macro("free") -#pragma pop_macro("malloc") -#pragma pop_macro("realloc") -#pragma pop_macro("_recalloc") -#pragma pop_macro("_aligned_free") -#pragma pop_macro("_aligned_malloc") -#pragma pop_macro("_aligned_offset_malloc") -#pragma pop_macro("_aligned_realloc") -#pragma pop_macro("_aligned_recalloc") -#pragma pop_macro("_aligned_offset_realloc") -#pragma pop_macro("_aligned_offset_recalloc") -#pragma pop_macro("_aligned_msize") -#endif diff --git a/beast/module/core/core.unity.mm b/beast/module/core/core.unity.mm deleted file mode 100644 index 2875d31481..0000000000 --- a/beast/module/core/core.unity.mm +++ /dev/null @@ -1,30 +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. -*/ -//============================================================================== - -#undef BEAST_COMPILE_OBJECTIVE_CPP -#define BEAST_COMPILE_OBJECTIVE_CPP 1 - -#include "beast_core.unity.cpp" - -#undef BEAST_COMPILE_OBJECTIVE_CPP -#define BEAST_COMPILE_OBJECTIVE_CPP 0 diff --git a/beast/module/core/diagnostic/FatalError.cpp b/beast/module/core/diagnostic/FatalError.cpp deleted file mode 100644 index 146041b774..0000000000 --- a/beast/module/core/diagnostic/FatalError.cpp +++ /dev/null @@ -1,65 +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 - -#include -#include -#include -#include -#include - -namespace beast { - -//------------------------------------------------------------------------------ -[[noreturn]] -void -FatalError ( - char const* message, - char const* file, - int line) noexcept -{ - static std::mutex gate; - - // We only allow one thread to report a fatal error. Other threads that - // encounter fatal errors while we are reporting get blocked here. - std::lock_guard lock(gate); - - std::cerr << "An error has occurred. The application will terminate.\n"; - - if (message != nullptr && message [0] != 0) - std::cerr << "Message: " << message << '\n'; - - if (file != nullptr && file [0] != 0) - std::cerr << " File: " << file << ":" << line << '\n'; - - auto const backtrace = getStackBacktrace (); - - if (!backtrace.empty ()) - { - std::cerr << " Stack:" << std::endl; - - for (auto const& frame : backtrace) - std::cerr << " " << frame << '\n'; - } - - std::abort (); -} - -} // beast diff --git a/beast/module/core/diagnostic/FatalError.h b/beast/module/core/diagnostic/FatalError.h deleted file mode 100644 index 3d08ec6ee9..0000000000 --- a/beast/module/core/diagnostic/FatalError.h +++ /dev/null @@ -1,45 +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_MODULE_CORE_DIAGNOSTIC_FATALERROR_H_INCLUDED -#define BEAST_MODULE_CORE_DIAGNOSTIC_FATALERROR_H_INCLUDED - -namespace beast -{ - -/** Signal a fatal error. - - A fatal error indicates that the program has encountered an unexpected - situation and cannot continue safely. Reasons for raising a fatal error - would be to protect data integrity, prevent valuable resources from being - wasted, or to ensure that the user does not experience undefined behavior. - - If multiple threads raise an error, only one will succeed while the others - will be blocked before the process terminates. -*/ -[[noreturn]] -void -FatalError ( - char const* message, - char const* file = nullptr, - int line = 0) noexcept; - -} // beast - -#endif diff --git a/beast/module/core/diagnostic/MeasureFunctionCallTime.h b/beast/module/core/diagnostic/MeasureFunctionCallTime.h deleted file mode 100644 index 9671513d1b..0000000000 --- a/beast/module/core/diagnostic/MeasureFunctionCallTime.h +++ /dev/null @@ -1,42 +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_MODULE_CORE_DIAGNOSTIC_MEASUREFUNCTIONCALLTIME_H_INCLUDED -#define BEAST_MODULE_CORE_DIAGNOSTIC_MEASUREFUNCTIONCALLTIME_H_INCLUDED - -#include - -namespace beast -{ - -/** Measures the speed of invoking a function. */ -template -std::chrono::high_resolution_clock::duration -measureFunctionCallTime (Function f, Args&&... args) -{ - auto start = std::chrono::high_resolution_clock::now (); - f (std::forward(args)...); - auto end = std::chrono::high_resolution_clock::now (); - - return end - start; -} - -} // beast - -#endif diff --git a/beast/module/core/diagnostic/SemanticVersion.cpp b/beast/module/core/diagnostic/SemanticVersion.cpp deleted file mode 100644 index 3d136c4f8c..0000000000 --- a/beast/module/core/diagnostic/SemanticVersion.cpp +++ /dev/null @@ -1,562 +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 -#include - -#include -#include - -namespace beast { - -std::string print_identifiers (SemanticVersion::identifier_list const& list) -{ - std::string ret; - - for (auto const& x : list) - { - if (!ret.empty ()) - ret += "."; - ret += x; - } - - return ret; -} - -bool isNumeric (std::string const& s) -{ - int n; - - // Must be convertible to an integer - if (!lexicalCastChecked (n, s)) - return false; - - // Must not have leading zeroes - return std::to_string (n) == s; -} - -bool chop (std::string const& what, std::string& input) -{ - auto ret = input.find (what); - - if (ret != 0) - return false; - - input.erase (0, what.size ()); - return true; -} - -bool chopUInt (int& value, int limit, std::string& input) -{ - // Must not be empty - if (input.empty ()) - return false; - - auto left_iter = std::find_if_not (input.begin (), input.end (), - [](std::string::value_type c) - { - return std::isdigit (c, std::locale::classic()); - }); - - std::string item (input.begin (), left_iter); - - // Must not be empty - if (item.empty ()) - return false; - - int n; - - // Must be convertible to an integer - if (!lexicalCastChecked (n, item)) - return false; - - // Must not have leading zeroes - if (std::to_string (n) != item) - return false; - - // Must not be out of range - if (n < 0 || n > limit) - return false; - - input.erase (input.begin (), left_iter); - value = n; - - return true; -} - -bool extract_identifier ( - std::string& value, bool allowLeadingZeroes, std::string& input) -{ - // Must not be empty - if (input.empty ()) - return false; - - // Must not have a leading 0 - if (!allowLeadingZeroes && input [0] == '0') - return false; - - auto last = input.find_first_not_of ( - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"); - - // Must not be empty - if (last == 0) - return false; - - value = input.substr (0, last); - input.erase (0, last); - return true; -} - -bool extract_identifiers ( - SemanticVersion::identifier_list& identifiers, - bool allowLeadingZeroes, - std::string& input) -{ - if (input.empty ()) - return false; - - do { - std::string s; - - if (!extract_identifier (s, allowLeadingZeroes, input)) - return false; - identifiers.push_back (s); - } while (chop (".", input)); - - return true; -} - -//------------------------------------------------------------------------------ - -SemanticVersion::SemanticVersion () - : majorVersion (0) - , minorVersion (0) - , patchVersion (0) -{ -} - -SemanticVersion::SemanticVersion (std::string const& version) - : SemanticVersion () -{ - if (!parse (version)) - throw std::invalid_argument ("invalid version string"); -} - -bool SemanticVersion::parse (std::string const& input, bool debug) -{ - // May not have leading or trailing whitespace - auto left_iter = std::find_if_not (input.begin (), input.end (), - [](std::string::value_type c) - { - return std::isspace (c, std::locale::classic()); - }); - - auto right_iter = std::find_if_not (input.rbegin (), input.rend (), - [](std::string::value_type c) - { - return std::isspace (c, std::locale::classic()); - }).base (); - - // Must not be empty! - if (left_iter >= right_iter) - return false; - - std::string version (left_iter, right_iter); - - // May not have leading or trailing whitespace - if (version != input) - return false; - - // Must have major version number - if (! chopUInt (majorVersion, std::numeric_limits ::max (), version)) - return false; - if (! chop (".", version)) - return false; - - // Must have minor version number - if (! chopUInt (minorVersion, std::numeric_limits ::max (), version)) - return false; - if (! chop (".", version)) - return false; - - // Must have patch version number - if (! chopUInt (patchVersion, std::numeric_limits ::max (), version)) - return false; - - // May have pre-release identifier list - if (chop ("-", version)) - { - if (!extract_identifiers (preReleaseIdentifiers, false, version)) - return false; - - // Must not be empty - if (preReleaseIdentifiers.empty ()) - return false; - } - - // May have metadata identifier list - if (chop ("+", version)) - { - if (!extract_identifiers (metaData, true, version)) - return false; - - // Must not be empty - if (metaData.empty ()) - return false; - } - - return version.empty (); -} - -std::string SemanticVersion::print () const -{ - std::string s; - - s = std::to_string (majorVersion) + "." + - std::to_string (minorVersion) + "." + - std::to_string (patchVersion); - - if (!preReleaseIdentifiers.empty ()) - { - s += "-"; - s += print_identifiers (preReleaseIdentifiers); - } - - if (!metaData.empty ()) - { - s += "+"; - s += print_identifiers (metaData); - } - - return s; -} - -int compare (SemanticVersion const& lhs, SemanticVersion const& rhs) -{ - if (lhs.majorVersion > rhs.majorVersion) - return 1; - else if (lhs.majorVersion < rhs.majorVersion) - return -1; - - if (lhs.minorVersion > rhs.minorVersion) - return 1; - else if (lhs.minorVersion < rhs.minorVersion) - return -1; - - if (lhs.patchVersion > rhs.patchVersion) - return 1; - else if (lhs.patchVersion < rhs.patchVersion) - return -1; - - if (lhs.isPreRelease () || rhs.isPreRelease ()) - { - // Pre-releases have a lower precedence - if (lhs.isRelease () && rhs.isPreRelease ()) - return 1; - else if (lhs.isPreRelease () && rhs.isRelease ()) - return -1; - - // Compare pre-release identifiers - for (int i = 0; i < std::max (lhs.preReleaseIdentifiers.size (), rhs.preReleaseIdentifiers.size ()); ++i) - { - // A larger list of identifiers has a higher precedence - if (i >= rhs.preReleaseIdentifiers.size ()) - return 1; - else if (i >= lhs.preReleaseIdentifiers.size ()) - return -1; - - std::string const& left (lhs.preReleaseIdentifiers [i]); - std::string const& right (rhs.preReleaseIdentifiers [i]); - - // Numeric identifiers have lower precedence - if (! isNumeric (left) && isNumeric (right)) - return 1; - else if (isNumeric (left) && ! isNumeric (right)) - return -1; - - if (isNumeric (left)) - { - assert(isNumeric (right)); - - int const iLeft (lexicalCastThrow (left)); - int const iRight (lexicalCastThrow (right)); - - if (iLeft > iRight) - return 1; - else if (iLeft < iRight) - return -1; - } - else - { - assert (! isNumeric (right)); - - int result = left.compare (right); - - if (result != 0) - return result; - } - } - } - - // metadata is ignored - - return 0; -} - -//------------------------------------------------------------------------------ - -class SemanticVersion_test: public unit_test::suite -{ - using identifier_list = SemanticVersion::identifier_list; - -public: - void checkPass (std::string const& input, bool shouldPass = true) - { - SemanticVersion v; - - if (shouldPass ) - { - expect (v.parse (input)); - expect (v.print () == input); - } - else - { - expect (! v.parse (input)); - } - } - - void checkFail (std::string const& input) - { - checkPass (input, false); - } - - // check input and input with appended metadata - void checkMeta (std::string const& input, bool shouldPass) - { - checkPass (input, shouldPass); - - checkPass (input + "+a", shouldPass); - checkPass (input + "+1", shouldPass); - checkPass (input + "+a.b", shouldPass); - checkPass (input + "+ab.cd", shouldPass); - - checkFail (input + "!"); - checkFail (input + "+"); - checkFail (input + "++"); - checkFail (input + "+!"); - checkFail (input + "+."); - checkFail (input + "+a.!"); - } - - void checkMetaFail (std::string const& input) - { - checkMeta (input, false); - } - - // check input, input with appended release data, - // input with appended metadata, and input with both - // appended release data and appended metadata - // - void checkRelease (std::string const& input, bool shouldPass = true) - { - checkMeta (input, shouldPass); - - checkMeta (input + "-1", shouldPass); - checkMeta (input + "-a", shouldPass); - checkMeta (input + "-a1", shouldPass); - checkMeta (input + "-a1.b1", shouldPass); - checkMeta (input + "-ab.cd", shouldPass); - checkMeta (input + "--", shouldPass); - - checkMetaFail (input + "+"); - checkMetaFail (input + "!"); - checkMetaFail (input + "-"); - checkMetaFail (input + "-!"); - checkMetaFail (input + "-."); - checkMetaFail (input + "-a.!"); - checkMetaFail (input + "-0.a"); - } - - // Checks the major.minor.version string alone and with all - // possible combinations of release identifiers and metadata. - // - void check (std::string const& input, bool shouldPass = true) - { - checkRelease (input, shouldPass); - } - - void negcheck (std::string const& input) - { - check (input, false); - } - - void testParse () - { - testcase ("parsing"); - - check ("0.0.0"); - check ("1.2.3"); - check ("2147483647.2147483647.2147483647"); // max int - - // negative values - negcheck ("-1.2.3"); - negcheck ("1.-2.3"); - negcheck ("1.2.-3"); - - // missing parts - negcheck (""); - negcheck ("1"); - negcheck ("1."); - negcheck ("1.2"); - negcheck ("1.2."); - negcheck (".2.3"); - - // whitespace - negcheck (" 1.2.3"); - negcheck ("1 .2.3"); - negcheck ("1.2 .3"); - negcheck ("1.2.3 "); - - // leading zeroes - negcheck ("01.2.3"); - negcheck ("1.02.3"); - negcheck ("1.2.03"); - } - - static identifier_list ids () - { - return identifier_list (); - } - - static identifier_list ids ( - std::string const& s1) - { - identifier_list v; - v.push_back (s1); - return v; - } - - static identifier_list ids ( - std::string const& s1, std::string const& s2) - { - identifier_list v; - v.push_back (s1); - v.push_back (s2); - return v; - } - - static identifier_list ids ( - std::string const& s1, std::string const& s2, std::string const& s3) - { - identifier_list v; - v.push_back (s1); - v.push_back (s2); - v.push_back (s3); - return v; - } - - // Checks the decomposition of the input into appropriate values - void checkValues (std::string const& input, - int majorVersion, - int minorVersion, - int patchVersion, - identifier_list const& preReleaseIdentifiers = identifier_list (), - identifier_list const& metaData = identifier_list ()) - { - SemanticVersion v; - - expect (v.parse (input)); - - expect (v.majorVersion == majorVersion); - expect (v.minorVersion == minorVersion); - expect (v.patchVersion == patchVersion); - - expect (v.preReleaseIdentifiers == preReleaseIdentifiers); - expect (v.metaData == metaData); - } - - void testValues () - { - testcase ("values"); - - checkValues ("0.1.2", 0, 1, 2); - checkValues ("1.2.3", 1, 2, 3); - checkValues ("1.2.3-rc1", 1, 2, 3, ids ("rc1")); - checkValues ("1.2.3-rc1.debug", 1, 2, 3, ids ("rc1", "debug")); - checkValues ("1.2.3-rc1.debug.asm", 1, 2, 3, ids ("rc1", "debug", "asm")); - checkValues ("1.2.3+full", 1, 2, 3, ids (), ids ("full")); - checkValues ("1.2.3+full.prod", 1, 2, 3, ids (), ids ("full", "prod")); - checkValues ("1.2.3+full.prod.x86", 1, 2, 3, ids (), ids ("full", "prod", "x86")); - checkValues ("1.2.3-rc1.debug.asm+full.prod.x86", 1, 2, 3, - ids ("rc1", "debug", "asm"), ids ("full", "prod", "x86")); - } - - // makes sure the left version is less than the right - void checkLessInternal (std::string const& lhs, std::string const& rhs) - { - SemanticVersion left; - SemanticVersion right; - - expect (left.parse (lhs)); - expect (right.parse (rhs)); - - expect (compare (left, left) == 0); - expect (compare (right, right) == 0); - expect (compare (left, right) < 0); - expect (compare (right, left) > 0); - - expect (left < right); - expect (right > left); - expect (left == left); - expect (right == right); - } - - void checkLess (std::string const& lhs, std::string const& rhs) - { - checkLessInternal (lhs, rhs); - checkLessInternal (lhs + "+meta", rhs); - checkLessInternal (lhs, rhs + "+meta"); - checkLessInternal (lhs + "+meta", rhs + "+meta"); - } - - void testCompare () - { - testcase ("comparisons"); - - checkLess ("1.0.0-alpha", "1.0.0-alpha.1"); - checkLess ("1.0.0-alpha.1", "1.0.0-alpha.beta"); - checkLess ("1.0.0-alpha.beta", "1.0.0-beta"); - checkLess ("1.0.0-beta", "1.0.0-beta.2"); - checkLess ("1.0.0-beta.2", "1.0.0-beta.11"); - checkLess ("1.0.0-beta.11", "1.0.0-rc.1"); - checkLess ("1.0.0-rc.1", "1.0.0"); - checkLess ("0.9.9", "1.0.0"); - } - - void run () - { - testParse (); - testValues (); - testCompare (); - } -}; - -BEAST_DEFINE_TESTSUITE(SemanticVersion,beast_core,beast); - -} // beast diff --git a/beast/module/core/diagnostic/SemanticVersion.h b/beast/module/core/diagnostic/SemanticVersion.h deleted file mode 100644 index 9fa8e57a19..0000000000 --- a/beast/module/core/diagnostic/SemanticVersion.h +++ /dev/null @@ -1,113 +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_MODULE_CORE_DIAGNOSTIC_SEMANTICVERSION_H_INCLUDED -#define BEAST_MODULE_CORE_DIAGNOSTIC_SEMANTICVERSION_H_INCLUDED - -#include -#include - -namespace beast { - -/** A Semantic Version number. - - Identifies the build of a particular version of software using - the Semantic Versioning Specification described here: - - http://semver.org/ -*/ -class SemanticVersion -{ -public: - using identifier_list = std::vector; - - int majorVersion; - int minorVersion; - int patchVersion; - - identifier_list preReleaseIdentifiers; - identifier_list metaData; - - SemanticVersion (); - - SemanticVersion (std::string const& version); - - /** Parse a semantic version string. - The parsing is as strict as possible. - @return `true` if the string was parsed. - */ - bool parse (std::string const& input, bool debug = false); - - /** Produce a string from semantic version components. */ - std::string print () const; - - inline bool isRelease () const noexcept - { - return preReleaseIdentifiers.empty(); - } - inline bool isPreRelease () const noexcept - { - return !isRelease (); - } -}; - -/** Compare two SemanticVersions against each other. - The comparison follows the rules as per the specification. -*/ -int compare (SemanticVersion const& lhs, SemanticVersion const& rhs); - -inline bool -operator== (SemanticVersion const& lhs, SemanticVersion const& rhs) -{ - return compare (lhs, rhs) == 0; -} - -inline bool -operator!= (SemanticVersion const& lhs, SemanticVersion const& rhs) -{ - return compare (lhs, rhs) != 0; -} - -inline bool -operator>= (SemanticVersion const& lhs, SemanticVersion const& rhs) -{ - return compare (lhs, rhs) >= 0; -} - -inline bool -operator<= (SemanticVersion const& lhs, SemanticVersion const& rhs) -{ - return compare (lhs, rhs) <= 0; -} - -inline bool -operator> (SemanticVersion const& lhs, SemanticVersion const& rhs) -{ - return compare (lhs, rhs) > 0; -} - -inline bool -operator< (SemanticVersion const& lhs, SemanticVersion const& rhs) -{ - return compare (lhs, rhs) < 0; -} - -} // beast - -#endif diff --git a/beast/module/core/diagnostic/UnitTestUtilities.cpp b/beast/module/core/diagnostic/UnitTestUtilities.cpp deleted file mode 100644 index f40a382f13..0000000000 --- a/beast/module/core/diagnostic/UnitTestUtilities.cpp +++ /dev/null @@ -1,24 +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. -*/ -//============================================================================== - -namespace beast { -namespace UnitTestUtilities { - -} // UnitTestUtilities -} // beast diff --git a/beast/module/core/logging/Logger.h b/beast/module/core/logging/Logger.h deleted file mode 100644 index a7ae706437..0000000000 --- a/beast/module/core/logging/Logger.h +++ /dev/null @@ -1,34 +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_MODULE_CORE_LOGGING_LOGGER_H_INCLUDED -#define BEAST_MODULE_CORE_LOGGING_LOGGER_H_INCLUDED - -namespace beast -{ - -void outputDebugString (std::string const& text); - -} // beast - -#endif // BEAST_LOGGER_H_INCLUDED diff --git a/beast/module/core/native/BasicNativeHeaders.h b/beast/module/core/native/BasicNativeHeaders.h deleted file mode 100644 index 152fed561f..0000000000 --- a/beast/module/core/native/BasicNativeHeaders.h +++ /dev/null @@ -1,230 +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_MODULE_CORE_NATIVE_BASICNATIVEHEADERS_H_INCLUDED -#define BEAST_MODULE_CORE_NATIVE_BASICNATIVEHEADERS_H_INCLUDED - -#include - -#undef T - -//============================================================================== -#if BEAST_MAC || BEAST_IOS - - #if BEAST_IOS - #import - #import - #import - #import - #include - #else - #define Point CarbonDummyPointName - #define Component CarbonDummyCompName - #import - #import - #undef Point - #undef Component - #include - #endif - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - -//============================================================================== -#elif BEAST_WINDOWS - #if BEAST_MSVC - #ifndef _CPPRTTI - #error "Beast requires RTTI!" - #endif - - #ifndef _CPPUNWIND - #error "Beast requires RTTI!" - #endif - - #pragma warning (push) - #pragma warning (disable : 4100 4201 4514 4312 4995) - #endif - - #define STRICT 1 - #define WIN32_LEAN_AND_MEAN 1 - #ifndef _WIN32_WINNT - #if BEAST_MINGW - #define _WIN32_WINNT 0x0501 - #else - #define _WIN32_WINNT 0x0600 - #endif - #endif - #define _UNICODE 1 - #define UNICODE 1 - #ifndef _WIN32_IE - #define _WIN32_IE 0x0400 - #endif - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #pragma warning ( push ) - #pragma warning ( disable: 4091 ) - #include - #pragma warning ( pop ) - #include - #include - - #if BEAST_MINGW - #include - #else - #include - #include - #endif - - #undef PACKED - - #if BEAST_MSVC - #pragma warning (pop) - #pragma warning (4: 4511 4512 4100 /*4365*/) // (enable some warnings that are turned off in VC8) - #endif - - #if BEAST_MSVC && ! BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES - #pragma comment (lib, "kernel32.lib") - #pragma comment (lib, "user32.lib") - #pragma comment (lib, "wininet.lib") - #pragma comment (lib, "advapi32.lib") - #pragma comment (lib, "ws2_32.lib") - #pragma comment (lib, "version.lib") - #pragma comment (lib, "shlwapi.lib") - #pragma comment (lib, "winmm.lib") - - #ifdef _NATIVE_WCHAR_T_DEFINED - #ifdef _DEBUG - #pragma comment (lib, "comsuppwd.lib") - #else - #pragma comment (lib, "comsuppw.lib") - #endif - #else - #ifdef _DEBUG - #pragma comment (lib, "comsuppd.lib") - #else - #pragma comment (lib, "comsupp.lib") - #endif - #endif - #endif - -//============================================================================== -#elif BEAST_LINUX || BEAST_BSD - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - #if BEAST_BSD - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - // This has to be in the global namespace - extern char** environ; - - #else - #include - #include - #include - #include - #endif - -//============================================================================== -#elif BEAST_ANDROID - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#endif - -// Need to clear various moronic redefinitions made by system headers.. -#undef max -#undef min -#undef direct -#undef check - -#endif // BEAST_BASICNATIVEHEADERS_H_INCLUDED diff --git a/beast/module/core/native/bsd_SystemStats.cpp b/beast/module/core/native/bsd_SystemStats.cpp deleted file mode 100644 index 99ced4c636..0000000000 --- a/beast/module/core/native/bsd_SystemStats.cpp +++ /dev/null @@ -1,40 +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. -*/ - -//============================================================================== - -void outputDebugString (std::string const& text) -{ - std::cerr << text << std::endl; -} - -//============================================================================== -std::string getComputerName() -{ - char name [256] = { 0 }; - if (gethostname (name, sizeof (name) - 1) == 0) - return name; - - return std::string{}; -} - -} // beast diff --git a/beast/module/core/native/linux_SystemStats.cpp b/beast/module/core/native/linux_SystemStats.cpp deleted file mode 100644 index 4814169c66..0000000000 --- a/beast/module/core/native/linux_SystemStats.cpp +++ /dev/null @@ -1,42 +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. -*/ -//============================================================================== - -namespace beast -{ - -void outputDebugString (std::string const& text) -{ - std::cerr << text << std::endl; -} - -//============================================================================== -std::string getComputerName() -{ - char name [256] = { 0 }; - if (gethostname (name, sizeof (name) - 1) == 0) - return name; - - return std::string{}; -} - -} // beast diff --git a/beast/module/core/native/mac_SystemStats.mm b/beast/module/core/native/mac_SystemStats.mm deleted file mode 100644 index 07dbd7d4e7..0000000000 --- a/beast/module/core/native/mac_SystemStats.mm +++ /dev/null @@ -1,76 +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. -*/ -//============================================================================== - -namespace beast -{ - -ScopedAutoReleasePool::ScopedAutoReleasePool() -{ - pool = [[NSAutoreleasePool alloc] init]; -} - -ScopedAutoReleasePool::~ScopedAutoReleasePool() -{ - [((NSAutoreleasePool*) pool) release]; -} - -//============================================================================== -void outputDebugString (std::string const& text) -{ - // Would prefer to use std::cerr here, but avoiding it for - // the moment, due to clang JIT linkage problems. - fputs (text.c_str (), stderr); - fputs ("\n", stderr); - fflush (stderr); -} - -//============================================================================== - -#if BEAST_MAC -struct RLimitInitialiser -{ - RLimitInitialiser() - { - rlimit lim; - getrlimit (RLIMIT_NOFILE, &lim); - lim.rlim_cur = lim.rlim_max = RLIM_INFINITY; - setrlimit (RLIMIT_NOFILE, &lim); - } -}; - -static RLimitInitialiser rLimitInitialiser; -#endif - -//============================================================================== -std::string getComputerName() -{ - // FIXME: Remove ".local" from the name - char name [256] = { 0 }; - - if (gethostname (name, sizeof (name) - 1) == 0) - return name; - - return std::string{}; -} - -} // beast diff --git a/beast/module/core/native/osx_ObjCHelpers.h b/beast/module/core/native/osx_ObjCHelpers.h deleted file mode 100644 index 4b9599e98c..0000000000 --- a/beast/module/core/native/osx_ObjCHelpers.h +++ /dev/null @@ -1,54 +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_MODULE_CORE_NATIVE_OSX_OBJCHELPERS_H_INCLUDED -#define BEAST_MODULE_CORE_NATIVE_OSX_OBJCHELPERS_H_INCLUDED - -#include -#include - -namespace beast -{ - -/* This file contains a few helper functions that are used internally but which - need to be kept away from the public headers because they use obj-C symbols. -*/ -namespace -{ - static inline NSString* stringToNS (std::string const& s) - { -#ifndef NDEBUG - // The UTF-8 encoding function for ASCII characters - // in the range [0-127] is the identity. We are more - // strict and require only printable characters. - for (auto const& c : s) - assert (isprint(c)); -#endif - - return [NSString stringWithUTF8String: s.c_str()]; - } -} - -} // beast - -#endif // BEAST_OSX_OBJCHELPERS_H_INCLUDED diff --git a/beast/module/core/native/win32_SystemStats.cpp b/beast/module/core/native/win32_SystemStats.cpp deleted file mode 100644 index 1edd41bb80..0000000000 --- a/beast/module/core/native/win32_SystemStats.cpp +++ /dev/null @@ -1,42 +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. -*/ -//============================================================================== - -namespace beast -{ - -void outputDebugString (std::string const& text) -{ - OutputDebugStringA ((text + "\n").c_str ()); -} - -//============================================================================== -std::string getComputerName() -{ - char text [MAX_COMPUTERNAME_LENGTH + 2] = { 0 }; - DWORD len = MAX_COMPUTERNAME_LENGTH + 1; - if (!GetComputerNameA (text, &len)) - text[0] = 0; - return text; -} - -} // beast diff --git a/beast/module/core/system/StandardIncludes.h b/beast/module/core/system/StandardIncludes.h deleted file mode 100644 index a714de1c09..0000000000 --- a/beast/module/core/system/StandardIncludes.h +++ /dev/null @@ -1,78 +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_MODULE_CORE_SYSTEM_STANDARDINCLUDES_H_INCLUDED -#define BEAST_MODULE_CORE_SYSTEM_STANDARDINCLUDES_H_INCLUDED - -// Include some common OS headers.. -#if BEAST_MSVC -#pragma warning (push) -#pragma warning (disable: 4514 4245 4100) -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// undef symbols that are sometimes set by misguided 3rd-party headers.. -#undef check -#undef TYPE_BOOL -#undef max -#undef min - -#endif diff --git a/beast/module/core/system/SystemStats.cpp b/beast/module/core/system/SystemStats.cpp deleted file mode 100644 index 53f00b1caa..0000000000 --- a/beast/module/core/system/SystemStats.cpp +++ /dev/null @@ -1,115 +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. -*/ -//============================================================================== - -#include -#include -#include - -// Some basic tests, to keep an eye on things and make sure these types work ok -// on all platforms. - -static_assert (sizeof (std::intptr_t) == sizeof (void*), "std::intptr_t must be the same size as void*"); - -static_assert (sizeof (std::int8_t) == 1, "std::int8_t must be exactly 1 byte!"); -static_assert (sizeof (std::int16_t) == 2, "std::int16_t must be exactly 2 bytes!"); -static_assert (sizeof (std::int32_t) == 4, "std::int32_t must be exactly 4 bytes!"); -static_assert (sizeof (std::int64_t) == 8, "std::int64_t must be exactly 8 bytes!"); - -static_assert (sizeof (std::uint8_t) == 1, "std::uint8_t must be exactly 1 byte!"); -static_assert (sizeof (std::uint16_t) == 2, "std::uint16_t must be exactly 2 bytes!"); -static_assert (sizeof (std::uint32_t) == 4, "std::uint32_t must be exactly 4 bytes!"); -static_assert (sizeof (std::uint64_t) == 8, "std::uint64_t must be exactly 8 bytes!"); - -namespace beast -{ -//============================================================================== -std::vector -getStackBacktrace() -{ - std::vector result; - -#if BEAST_ANDROID || BEAST_MINGW || BEAST_BSD - assert(false); // sorry, not implemented yet! - -#elif BEAST_WINDOWS - HANDLE process = GetCurrentProcess(); - SymInitialize (process, nullptr, TRUE); - - void* stack[128]; - int frames = (int) CaptureStackBackTrace (0, - std::distance(std::begin(stack), std::end(stack)), - stack, nullptr); - - HeapBlock symbol; - symbol.calloc (sizeof (SYMBOL_INFO) + 256, 1); - symbol->MaxNameLen = 255; - symbol->SizeOfStruct = sizeof (SYMBOL_INFO); - - for (int i = 0; i < frames; ++i) - { - DWORD64 displacement = 0; - - if (SymFromAddr (process, (DWORD64) stack[i], &displacement, symbol)) - { - std::string frame; - - frame.append (std::to_string (i) + ": "); - - IMAGEHLP_MODULE64 moduleInfo; - zerostruct (moduleInfo); - moduleInfo.SizeOfStruct = sizeof (moduleInfo); - - if (::SymGetModuleInfo64 (process, symbol->ModBase, &moduleInfo)) - { - frame.append (moduleInfo.ModuleName); - frame.append (": "); - } - - frame.append (symbol->Name); - - if (displacement) - { - frame.append ("+"); - frame.append (std::to_string (displacement)); - } - - result.push_back (frame); - } - } - -#else - void* stack[128]; - int frames = backtrace (stack, - std::distance(std::begin(stack), std::end(stack))); - - std::unique_ptr frame ( - backtrace_symbols (stack, frames), std::free); - - for (int i = 0; i < frames; ++i) - result.push_back (frame[i]); -#endif - - return result; -} - -} // beast diff --git a/beast/module/core/system/SystemStats.h b/beast/module/core/system/SystemStats.h deleted file mode 100644 index 0e6bd8ae2a..0000000000 --- a/beast/module/core/system/SystemStats.h +++ /dev/null @@ -1,44 +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_MODULE_CORE_SYSTEM_SYSTEMSTATS_H_INCLUDED -#define BEAST_MODULE_CORE_SYSTEM_SYSTEMSTATS_H_INCLUDED - -namespace beast -{ - -//============================================================================== -/** Returns the host-name of the computer. */ -std::string getComputerName(); - -//============================================================================== -/** Returns a backtrace of the current call-stack. - The usefulness of the result will depend on the level of debug symbols - that are available in the executable. -*/ -std::vector -getStackBacktrace(); - -} // beast - -#endif // BEAST_SYSTEMSTATS_H_INCLUDED diff --git a/beast/module/core/text/LexicalCast.cpp b/beast/module/core/text/LexicalCast.cpp deleted file mode 100644 index 64868dd305..0000000000 --- a/beast/module/core/text/LexicalCast.cpp +++ /dev/null @@ -1,281 +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 -#include - -namespace beast { - -class LexicalCast_test : public unit_test::suite -{ -public: - template - static IntType nextRandomInt (xor_shift_engine& r) - { - return static_cast (r()); - } - - template - void testInteger (IntType in) - { - std::string s; - IntType out (in+1); - - expect (lexicalCastChecked (s, in)); - expect (lexicalCastChecked (out, s)); - expect (out == in); - } - - template - void testIntegers (xor_shift_engine& r) - { - { - std::stringstream ss; - ss << - "random " << typeid (IntType).name (); - testcase (ss.str()); - - for (int i = 0; i < 1000; ++i) - { - IntType const value (nextRandomInt (r)); - testInteger (value); - } - } - - { - std::stringstream ss; - ss << - "numeric_limits <" << typeid (IntType).name () << ">"; - testcase (ss.str()); - - testInteger (std::numeric_limits ::min ()); - testInteger (std::numeric_limits ::max ()); - } - } - - void testPathologies() - { - testcase("pathologies"); - try - { - lexicalCastThrow("\xef\xbc\x91\xef\xbc\x90"); // utf-8 encoded - } - catch(BadLexicalCast const&) - { - pass(); - } - } - - template - void tryBadConvert (std::string const& s) - { - T out; - expect (!lexicalCastChecked (out, s), s); - } - - void testConversionOverflows() - { - testcase ("conversion overflows"); - - tryBadConvert ("99999999999999999999"); - tryBadConvert ("4294967300"); - tryBadConvert ("75821"); - } - - void testConversionUnderflows () - { - testcase ("conversion underflows"); - - tryBadConvert ("-1"); - - tryBadConvert ("-99999999999999999999"); - tryBadConvert ("-4294967300"); - tryBadConvert ("-75821"); - } - - template - bool tryEdgeCase (std::string const& s) - { - T ret; - - bool const result = lexicalCastChecked (ret, s); - - if (!result) - return false; - - return s == std::to_string (ret); - } - - void testEdgeCases () - { - testcase ("conversion edge cases"); - - expect(tryEdgeCase ("18446744073709551614")); - expect(tryEdgeCase ("18446744073709551615")); - expect(!tryEdgeCase ("18446744073709551616")); - - expect(tryEdgeCase ("9223372036854775806")); - expect(tryEdgeCase ("9223372036854775807")); - expect(!tryEdgeCase ("9223372036854775808")); - - expect(tryEdgeCase ("-9223372036854775807")); - expect(tryEdgeCase ("-9223372036854775808")); - expect(!tryEdgeCase ("-9223372036854775809")); - - expect(tryEdgeCase ("4294967294")); - expect(tryEdgeCase ("4294967295")); - expect(!tryEdgeCase ("4294967296")); - - expect(tryEdgeCase ("2147483646")); - expect(tryEdgeCase ("2147483647")); - expect(!tryEdgeCase ("2147483648")); - - expect(tryEdgeCase ("-2147483647")); - expect(tryEdgeCase ("-2147483648")); - expect(!tryEdgeCase ("-2147483649")); - - expect(tryEdgeCase ("65534")); - expect(tryEdgeCase ("65535")); - expect(!tryEdgeCase ("65536")); - - expect(tryEdgeCase ("32766")); - expect(tryEdgeCase ("32767")); - expect(!tryEdgeCase ("32768")); - - expect(tryEdgeCase ("-32767")); - expect(tryEdgeCase ("-32768")); - expect(!tryEdgeCase ("-32769")); - } - - template - void testThrowConvert(std::string const& s, bool success) - { - bool result = !success; - T out; - - try - { - out = lexicalCastThrow (s); - result = true; - } - catch(BadLexicalCast const&) - { - result = false; - } - - expect (result == success, s); - } - - void testThrowingConversions () - { - testcase ("throwing conversion"); - - testThrowConvert ("99999999999999999999", false); - testThrowConvert ("9223372036854775806", true); - - testThrowConvert ("4294967290", true); - testThrowConvert ("42949672900", false); - testThrowConvert ("429496729000", false); - testThrowConvert ("4294967290000", false); - - testThrowConvert ("5294967295", false); - testThrowConvert ("-2147483644", true); - - testThrowConvert ("66666", false); - testThrowConvert ("-5711", true); - } - - void testZero () - { - testcase ("zero conversion"); - - { - std::int32_t out; - - expect (lexicalCastChecked (out, "-0"), "0"); - expect (lexicalCastChecked (out, "0"), "0"); - expect (lexicalCastChecked (out, "+0"), "0"); - } - - { - std::uint32_t out; - - expect (!lexicalCastChecked (out, "-0"), "0"); - expect (lexicalCastChecked (out, "0"), "0"); - expect (lexicalCastChecked (out, "+0"), "0"); - } - } - - void testEntireRange () - { - testcase ("entire range"); - - std::int32_t i = std::numeric_limits::min(); - std::string const empty(""); - - while (i <= std::numeric_limits::max()) - { - std::int16_t j = static_cast(i); - - auto actual = std::to_string (j); - - auto result = lexicalCast (j, empty); - - expect (result == actual, actual + " (string to integer)"); - - if (result == actual) - { - auto number = lexicalCast (result); - - if (number != j) - expect (false, actual + " (integer to string)"); - } - - i++; - } - } - - void run() - { - std::int64_t const seedValue = 50; - - xor_shift_engine r (seedValue); - - testIntegers (r); - testIntegers (r); - testIntegers (r); - testIntegers (r); - testIntegers (r); - testIntegers (r); - testIntegers (r); - testIntegers (r); - - testPathologies(); - testConversionOverflows (); - testConversionUnderflows (); - testThrowingConversions (); - testZero (); - testEdgeCases (); - testEntireRange (); - } -}; - -BEAST_DEFINE_TESTSUITE(LexicalCast,beast_core,beast); - -} // beast diff --git a/beast/module/core/text/LexicalCast.h b/beast/module/core/text/LexicalCast.h deleted file mode 100644 index 3aed3e01ed..0000000000 --- a/beast/module/core/text/LexicalCast.h +++ /dev/null @@ -1,287 +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_MODULE_CORE_TEXT_LEXICALCAST_H_INCLUDED -#define BEAST_MODULE_CORE_TEXT_LEXICALCAST_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { - -namespace detail { - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4800) -#pragma warning(disable: 4804) -#endif - -template -bool -parse_integral (Int& num, FwdIt first, FwdIt last, Accumulator accumulator) -{ - num = 0; - - if (first == last) - return false; - - while (first != last) - { - auto const c = *first++; - if (c < '0' || c > '9') - return false; - if (!accumulator(num, Int(c - '0'))) - return false; - } - - return true; -} - -template -bool -parse_negative_integral (Int& num, FwdIt first, FwdIt last) -{ - Int limit_value = std::numeric_limits ::min() / 10; - Int limit_digit = std::numeric_limits ::min() % 10; - - if (limit_digit < 0) - limit_digit = -limit_digit; - - return parse_integral (num, first, last, - [limit_value, limit_digit](Int& value, Int digit) - { - assert ((digit >= 0) && (digit <= 9)); - if (value < limit_value || (value == limit_value && digit > limit_digit)) - return false; - value = (value * 10) - digit; - return true; - }); -} - -template -bool -parse_positive_integral (Int& num, FwdIt first, FwdIt last) -{ - Int limit_value = std::numeric_limits ::max() / 10; - Int limit_digit = std::numeric_limits ::max() % 10; - - return parse_integral (num, first, last, - [limit_value, limit_digit](Int& value, Int digit) - { - assert ((digit >= 0) && (digit <= 9)); - if (value > limit_value || (value == limit_value && digit > limit_digit)) - return false; - value = (value * 10) + digit; - return true; - }); -} - -template -bool -parseSigned (IntType& result, FwdIt first, FwdIt last) -{ - static_assert(std::is_signed::value, - "You may only call parseSigned with a signed integral type."); - - if (first != last && *first == '-') - return parse_negative_integral (result, first + 1, last); - - if (first != last && *first == '+') - return parse_positive_integral (result, first + 1, last); - - return parse_positive_integral (result, first, last); -} - -template -bool -parseUnsigned (UIntType& result, FwdIt first, FwdIt last) -{ - static_assert(std::is_unsigned::value, - "You may only call parseUnsigned with an unsigned integral type."); - - if (first != last && *first == '+') - return parse_positive_integral (result, first + 1, last); - - return parse_positive_integral (result, first, last); -} - -//------------------------------------------------------------------------------ - -// These specializatons get called by the non-member functions to do the work -template -struct LexicalCast; - -// conversion to std::string -template -struct LexicalCast -{ - template - std::enable_if_t ::value, bool> - operator () (std::string& out, Arithmetic in) - { - out = std::to_string (in); - return true; - } - - template - std::enable_if_t ::value, bool> - operator () (std::string& out, Enumeration in) - { - out = std::to_string ( - static_cast > (in)); - return true; - } -}; - -// Parse std::string to number -template -struct LexicalCast -{ - static_assert (std::is_integral ::value, - "beast::LexicalCast can only be used with integral types"); - - template - std::enable_if_t ::value, bool> - operator () (Integral& out, std::string const& in) const - { - return parseUnsigned (out, in.begin(), in.end()); - } - - template - std::enable_if_t ::value, bool> - operator () (Integral& out, std::string const& in) const - { - return parseSigned (out, in.begin(), in.end()); - } - - bool - operator () (bool& out, std::string in) const - { - // Convert the input to lowercase - std::transform(in.begin (), in.end (), in.begin (), ::tolower); - - if (in == "1" || in == "true") - { - out = true; - return true; - } - - if (in == "0" || in == "false") - { - out = false; - return true; - } - - return false; - } -}; - -//------------------------------------------------------------------------------ - -// Conversion from null terminated char const* -template -struct LexicalCast -{ - bool operator() (Out& out, char const* in) const - { - return LexicalCast ()(out, in); - } -}; - -// Conversion from null terminated char* -// The string is not modified. -template -struct LexicalCast -{ - bool operator() (Out& out, char* in) const - { - return LexicalCast ()(out, in); - } -}; - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -} // detail - -//------------------------------------------------------------------------------ - -/** Thrown when a conversion is not possible with LexicalCast. - Only used in the throw variants of lexicalCast. -*/ -struct BadLexicalCast : public std::bad_cast -{ -}; - -/** Intelligently convert from one type to another. - @return `false` if there was a parsing or range error -*/ -template -bool lexicalCastChecked (Out& out, In in) -{ - return detail::LexicalCast () (out, in); -} - -/** Convert from one type to another, throw on error - - An exception of type BadLexicalCast is thrown if the conversion fails. - - @return The new type. -*/ -template -Out lexicalCastThrow (In in) -{ - Out out; - - if (lexicalCastChecked (out, in)) - return out; - - throw BadLexicalCast (); -} - -/** Convert from one type to another. - - @param defaultValue The value returned if parsing fails - @return The new type. -*/ -template -Out lexicalCast (In in, Out defaultValue = Out ()) -{ - Out out; - - if (lexicalCastChecked (out, in)) - return out; - - return defaultValue; -} - -} // beast - -#endif diff --git a/beast/module/core/thread/DeadlineTimer.cpp b/beast/module/core/thread/DeadlineTimer.cpp deleted file mode 100644 index 0a5acbd074..0000000000 --- a/beast/module/core/thread/DeadlineTimer.cpp +++ /dev/null @@ -1,257 +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 -#include -#include - -namespace beast -{ - -class DeadlineTimer::Manager - : protected Thread -{ -private: - using Items = List ; - -public: - Manager () : Thread ("DeadlineTimer::Manager") - { - startThread (); - } - - ~Manager () - { - signalThreadShouldExit (); - notify (); - waitForThreadToExit (); - assert (m_items.empty ()); - } - - static - Manager& - instance() - { - static Manager m; - return m; - } - - // Okay to call on an active timer. - // However, an extra notification may still happen due to concurrency. - // - void activate (DeadlineTimer& timer, - double secondsRecurring, RelativeTime const& when) - { - assert (secondsRecurring >= 0); - - std::lock_guard lock (m_mutex); - - if (timer.m_isActive) - { - m_items.erase (m_items.iterator_to (timer)); - - timer.m_isActive = false; - } - - timer.m_secondsRecurring = secondsRecurring; - timer.m_notificationTime = when; - - insertSorted (timer); - timer.m_isActive = true; - - notify (); - } - - // Okay to call this on an inactive timer. - // This can happen naturally based on concurrency. - // - void deactivate (DeadlineTimer& timer) - { - std::lock_guard lock (m_mutex); - - if (timer.m_isActive) - { - m_items.erase (m_items.iterator_to (timer)); - - timer.m_isActive = false; - - notify (); - } - } - - void run () - { - while (! threadShouldExit ()) - { - RelativeTime const currentTime ( - RelativeTime::fromStartup ()); - - double seconds (0); - DeadlineTimer* timer (nullptr); - - { - std::lock_guard lock (m_mutex); - - // See if a timer expired - if (! m_items.empty ()) - { - timer = &m_items.front (); - - // Has this timer expired? - if (timer->m_notificationTime <= currentTime) - { - // Expired, remove it from the list. - assert (timer->m_isActive); - m_items.pop_front (); - - // Is the timer recurring? - if (timer->m_secondsRecurring > 0) - { - // Yes so set the timer again. - timer->m_notificationTime = - currentTime + timer->m_secondsRecurring; - - // Put it back into the list as active - insertSorted (*timer); - } - else - { - // Not a recurring timer, deactivate it. - timer->m_isActive = false; - } - - timer->m_listener->onDeadlineTimer (*timer); - - // re-loop - seconds = -1; - } - else - { - seconds = ( - timer->m_notificationTime - currentTime).inSeconds (); - - // Can't be zero and come into the else clause. - assert (seconds != 0); - - // Don't call the listener - timer = nullptr; - } - } - } - - // Note that we have released the lock here. - - if (seconds > 0) - { - // Wait until interrupt or next timer. - // - int const milliSeconds (std::max ( - static_cast (seconds * 1000 + 0.5), 1)); - assert (milliSeconds > 0); - wait (milliSeconds); - } - else if (seconds == 0) - { - // Wait until interrupt - // - wait (); - } - else - { - // Do not wait. This can happen if the recurring timer duration - // is extremely short, or if a listener wastes too much time in - // their callback. - } - } - } - - // Caller is responsible for locking - void insertSorted (DeadlineTimer& timer) - { - if (! m_items.empty ()) - { - Items::iterator before = m_items.begin (); - - for (;;) - { - if (before->m_notificationTime >= timer.m_notificationTime) - { - m_items.insert (before, timer); - break; - } - - ++before; - - if (before == m_items.end ()) - { - m_items.push_back (timer); - break; - } - } - } - else - { - m_items.push_back (timer); - } - } - -private: - std::recursive_mutex m_mutex; - Items m_items; -}; - -//------------------------------------------------------------------------------ - -DeadlineTimer::DeadlineTimer (Listener* listener) - : m_listener (listener) - , m_isActive (false) -{ -} - -DeadlineTimer::~DeadlineTimer () -{ - Manager::instance().deactivate (*this); -} - -void DeadlineTimer::cancel () -{ - Manager::instance().deactivate (*this); -} - -void DeadlineTimer::setExpiration (double secondsUntilDeadline) -{ - assert (secondsUntilDeadline != 0); - - RelativeTime const when ( - RelativeTime::fromStartup() + secondsUntilDeadline); - - Manager::instance().activate (*this, 0, when); -} - -void DeadlineTimer::setRecurringExpiration (double secondsUntilDeadline) -{ - assert (secondsUntilDeadline != 0); - - RelativeTime const when ( - RelativeTime::fromStartup() + secondsUntilDeadline); - - Manager::instance().activate (*this, secondsUntilDeadline, when); -} - -} // beast diff --git a/beast/module/core/thread/DeadlineTimer.h b/beast/module/core/thread/DeadlineTimer.h deleted file mode 100644 index f674782270..0000000000 --- a/beast/module/core/thread/DeadlineTimer.h +++ /dev/null @@ -1,118 +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_MODULE_CORE_THREAD_DEADLINETIMER_H_INCLUDED -#define BEAST_MODULE_CORE_THREAD_DEADLINETIMER_H_INCLUDED - -#include - -namespace beast { - -/** Provides periodic or one time notifications at a specified time interval. -*/ -class DeadlineTimer - : public List ::Node -{ -public: - /** Listener for a deadline timer. - - The listener is called on an auxiliary thread. It is suggested - not to perform any time consuming operations during the call. - */ - // VFALCO TODO Perhaps allow construction using a ServiceQueue to use - // for notifications. - // - class Listener - { - public: - virtual void onDeadlineTimer (DeadlineTimer&) { } - }; - -public: - /** Create a deadline timer with the specified listener attached. - */ - explicit DeadlineTimer (Listener* listener); - - DeadlineTimer (DeadlineTimer const&) = delete; - DeadlineTimer& operator= (DeadlineTimer const&) = delete; - - ~DeadlineTimer (); - - /** Cancel all notifications. - It is okay to call this on an inactive timer. - @note It is guaranteed that no notifications will occur after this - function returns. - */ - void cancel (); - - /** Set the timer to go off once in the future. - If the timer is already active, this will reset it. - @note If the timer is already active, the old one might go off - before this function returns. - @param secondsUntilDeadline The number of seconds until the timer - will send a notification. This must be - greater than zero. - */ - /** @{ */ - void setExpiration (double secondsUntilDeadline); - - template - void setExpiration (std::chrono::duration const& amount) - { - setExpiration (std::chrono::duration_cast < - std::chrono::duration > (amount).count ()); - } - /** @} */ - - /** Set the timer to go off repeatedly with the specified frequency. - If the timer is already active, this will reset it. - @note If the timer is already active, the old one might go off - before this function returns. - @param secondsUntilDeadline The number of seconds until the timer - will send a notification. This must be - greater than zero. - */ - void setRecurringExpiration (double secondsUntilDeadline); - - /** Equality comparison. - Timers are equal if they have the same address. - */ - inline bool operator== (DeadlineTimer const& other) const - { - return this == &other; - } - - /** Inequality comparison. */ - inline bool operator!= (DeadlineTimer const& other) const - { - return this != &other; - } - -private: - class Manager; - - Listener* const m_listener; - bool m_isActive; - RelativeTime m_notificationTime; - double m_secondsRecurring; // non zero if recurring -}; - -} // beast - -#endif diff --git a/beast/module/core/thread/MutexTraits.h b/beast/module/core/thread/MutexTraits.h deleted file mode 100644 index 3bab49cfa5..0000000000 --- a/beast/module/core/thread/MutexTraits.h +++ /dev/null @@ -1,24 +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_MODULE_CORE_THREAD_MUTEXTRAITS_H_INCLUDED -#define BEAST_MODULE_CORE_THREAD_MUTEXTRAITS_H_INCLUDED - - -#endif diff --git a/beast/module/core/thread/Workers.cpp b/beast/module/core/thread/Workers.cpp deleted file mode 100644 index 7e78c6fa67..0000000000 --- a/beast/module/core/thread/Workers.cpp +++ /dev/null @@ -1,293 +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 -#include - -namespace beast { - -Workers::Workers ( - Callback& callback, - std::string const& threadNames, - int numberOfThreads) - : m_callback (callback) - , m_threadNames (threadNames) - , m_allPaused (true, true) - , m_semaphore (0) - , m_numberOfThreads (0) - , m_activeCount (0) - , m_pauseCount (0) - , m_runningTaskCount (0) -{ - setNumberOfThreads (numberOfThreads); -} - -Workers::~Workers () -{ - pauseAllThreadsAndWait (); - - deleteWorkers (m_everyone); -} - -int Workers::getNumberOfThreads () const noexcept -{ - return m_numberOfThreads; -} - -// VFALCO NOTE if this function is called quickly to reduce then -// increase the number of threads, it could result in -// more paused threads being created than expected. -// -void Workers::setNumberOfThreads (int numberOfThreads) -{ - if (m_numberOfThreads != numberOfThreads) - { - if (numberOfThreads > m_numberOfThreads) - { - // Increasing the number of working threads - - int const amount = numberOfThreads - m_numberOfThreads; - - for (int i = 0; i < amount; ++i) - { - // See if we can reuse a paused worker - Worker* worker = m_paused.pop_front (); - - if (worker != nullptr) - { - // If we got here then the worker thread is at [1] - // This will unblock their call to wait() - // - worker->notify (); - } - else - { - worker = new Worker (*this, m_threadNames); - } - - m_everyone.push_front (worker); - } - } - else if (numberOfThreads < m_numberOfThreads) - { - // Decreasing the number of working threads - - int const amount = m_numberOfThreads - numberOfThreads; - - for (int i = 0; i < amount; ++i) - { - ++m_pauseCount; - - // Pausing a thread counts as one "internal task" - m_semaphore.signal (); - } - } - - m_numberOfThreads = numberOfThreads; - } -} - -void Workers::pauseAllThreadsAndWait () -{ - setNumberOfThreads (0); - - m_allPaused.wait (); - - assert (numberOfCurrentlyRunningTasks () == 0); -} - -void Workers::addTask () -{ - m_semaphore.signal (); -} - -int Workers::numberOfCurrentlyRunningTasks () const noexcept -{ - return m_runningTaskCount.load (); -} - -void Workers::deleteWorkers (LockFreeStack & stack) -{ - for (;;) - { - Worker* const worker = stack.pop_front (); - - if (worker != nullptr) - { - // This call blocks until the thread orderly exits - delete worker; - } - else - { - break; - } - } -} - -//------------------------------------------------------------------------------ - -Workers::Worker::Worker (Workers& workers, std::string const& threadName) - : Thread (threadName) - , m_workers (workers) -{ - startThread (); -} - -Workers::Worker::~Worker () -{ - stopThread (); -} - -void Workers::Worker::run () -{ - while (! threadShouldExit ()) - { - // Increment the count of active workers, and if - // we are the first one then reset the "all paused" event - // - if (++m_workers.m_activeCount == 1) - m_workers.m_allPaused.reset (); - - for (;;) - { - // Acquire a task or "internal task." - // - m_workers.m_semaphore.wait (); - - // See if there's a pause request. This - // counts as an "internal task." - // - int pauseCount = m_workers.m_pauseCount.load (); - - if (pauseCount > 0) - { - // Try to decrement - pauseCount = --m_workers.m_pauseCount; - - if (pauseCount >= 0) - { - // We got paused - break; - } - else - { - // Undo our decrement - ++m_workers.m_pauseCount; - } - } - - // We couldn't pause so we must have gotten - // unblocked in order to process a task. - // - ++m_workers.m_runningTaskCount; - m_workers.m_callback.processTask (); - --m_workers.m_runningTaskCount; - - // Put the name back in case the callback changed it - Thread::setCurrentThreadName (Thread::getThreadName()); - } - - // Any worker that goes into the paused list must - // guarantee that it will eventually block on its - // event object. - // - m_workers.m_paused.push_front (this); - - // Decrement the count of active workers, and if we - // are the last one then signal the "all paused" event. - // - if (--m_workers.m_activeCount == 0) - m_workers.m_allPaused.signal (); - - Thread::setCurrentThreadName ("(" + getThreadName() + ")"); - - // [1] We will be here when the paused list is popped - // - // We block on our event object, a requirement of being - // put into the paused list. - // - // This will get signaled on either a reactivate or a stopThread() - // - wait (); - } -} - -//------------------------------------------------------------------------------ - -class Workers_test : public unit_test::suite -{ -public: - struct TestCallback : Workers::Callback - { - explicit TestCallback (int count_) - : finished (false, count_ == 0) - , count (count_) - { - } - - void processTask () - { - if (--count == 0) - finished.signal (); - } - - WaitableEvent finished; - std::atomic count; - }; - - void testThreads (int const threadCount) - { - testcase ("threadCount = " + std::to_string (threadCount)); - - TestCallback cb (threadCount); - - Workers w (cb, "Test", 0); - expect (w.getNumberOfThreads () == 0); - - w.setNumberOfThreads (threadCount); - expect (w.getNumberOfThreads () == threadCount); - - for (int i = 0; i < threadCount; ++i) - w.addTask (); - - // 10 seconds should be enough to finish on any system - // - bool signaled = cb.finished.wait (10 * 1000); - expect (signaled, "timed out"); - - w.pauseAllThreadsAndWait (); - - // We had better finished all our work! - expect (cb.count.load () == 0, "Did not complete task!"); - } - - void run () - { - testThreads (0); - testThreads (1); - testThreads (2); - testThreads (4); - testThreads (16); - testThreads (64); - } -}; - -BEAST_DEFINE_TESTSUITE(Workers,beast_core,beast); - -} // beast diff --git a/beast/module/core/thread/Workers.h b/beast/module/core/thread/Workers.h deleted file mode 100644 index c4901ec308..0000000000 --- a/beast/module/core/thread/Workers.h +++ /dev/null @@ -1,154 +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_MODULE_CORE_THREAD_WORKERS_H_INCLUDED -#define BEAST_MODULE_CORE_THREAD_WORKERS_H_INCLUDED - -#include -#include - -#include -#include -#include - -namespace beast { - -/** A group of threads that process tasks. -*/ -class Workers -{ -public: - /** Called to perform tasks as needed. */ - struct Callback - { - /** Perform a task. - - The call is made on a thread owned by Workers. It is important - that you only process one task from inside your callback. Each - call to addTask will result in exactly one call to processTask. - - @see Workers::addTask - */ - virtual void processTask () = 0; - }; - - /** Create the object. - - A number of initial threads may be optionally specified. The - default is to create one thread per CPU. - - @param threadNames The name given to each created worker thread. - */ - explicit Workers (Callback& callback, - std::string const& threadNames = "Worker", - int numberOfThreads = - static_cast(std::thread::hardware_concurrency())); - - ~Workers (); - - /** Retrieve the desired number of threads. - - This just returns the number of active threads that were requested. If - there was a recent call to setNumberOfThreads, the actual number of active - threads may be temporarily different from what was last requested. - - @note This function is not thread-safe. - */ - int getNumberOfThreads () const noexcept; - - /** Set the desired number of threads. - @note This function is not thread-safe. - */ - void setNumberOfThreads (int numberOfThreads); - - /** Pause all threads and wait until they are paused. - - If a thread is processing a task it will pause as soon as the task - completes. There may still be tasks signaled even after all threads - have paused. - - @note This function is not thread-safe. - */ - void pauseAllThreadsAndWait (); - - /** Add a task to be performed. - - Every call to addTask will eventually result in a call to - Callback::processTask unless the Workers object is destroyed or - the number of threads is never set above zero. - - @note This function is thread-safe. - */ - void addTask (); - - /** Get the number of currently executing calls of Callback::processTask. - While this function is thread-safe, the value may not stay - accurate for very long. It's mainly for diagnostic purposes. - */ - int numberOfCurrentlyRunningTasks () const noexcept; - - //-------------------------------------------------------------------------- - -private: - struct PausedTag { }; - - /* A Worker executes tasks on its provided thread. - - These are the states: - - Active: Running the task processing loop. - Idle: Active, but blocked on waiting for a task. - Pausd: Blocked waiting to exit or become active. - */ - class Worker - : public LockFreeStack ::Node - , public LockFreeStack ::Node - , public Thread - { - public: - Worker (Workers& workers, std::string const& threadName); - - ~Worker (); - - private: - void run (); - - private: - Workers& m_workers; - }; - -private: - static void deleteWorkers (LockFreeStack & stack); - -private: - Callback& m_callback; - std::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 - int m_numberOfThreads; // how many we want active now - std::atomic m_activeCount; // to know when all are paused - std::atomic m_pauseCount; // how many threads need to pause now - std::atomic m_runningTaskCount; // how many calls to processTask() active - LockFreeStack m_everyone; // holds all created workers - LockFreeStack m_paused; // holds just paused workers -}; - -} // beast - -#endif diff --git a/beast/module/core/threads/ScopedLock.h b/beast/module/core/threads/ScopedLock.h deleted file mode 100644 index ca52e582a7..0000000000 --- a/beast/module/core/threads/ScopedLock.h +++ /dev/null @@ -1,258 +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_MODULE_CORE_THREADS_SCOPEDLOCK_H_INCLUDED -#define BEAST_MODULE_CORE_THREADS_SCOPEDLOCK_H_INCLUDED - -namespace beast -{ - -//============================================================================== -/** - Automatically locks and unlocks a mutex object. - - Use one of these as a local variable to provide RAII-based locking of a mutex. - - The templated class could be a CriticalSection, SpinLock, or anything else that - provides enter() and exit() methods. - - e.g. @code - CriticalSection myCriticalSection; - - for (;;) - { - const GenericScopedLock myScopedLock (myCriticalSection); - // myCriticalSection is now locked - - ...do some stuff... - - // myCriticalSection gets unlocked here. - } - @endcode - - @see GenericScopedUnlock, CriticalSection, SpinLock, ScopedLock, ScopedUnlock -*/ -template -class GenericScopedLock -{ -public: - //============================================================================== - /** Creates a GenericScopedLock. - - As soon as it is created, this will acquire the lock, and when the GenericScopedLock - object is deleted, the lock will be released. - - Make sure this object is created and deleted by the same thread, - otherwise there are no guarantees what will happen! Best just to use it - as a local stack object, rather than creating one with the new() operator. - */ - inline explicit GenericScopedLock (const LockType& lock) noexcept - : lock_ (lock) - { - lock.enter(); - } - - GenericScopedLock (GenericScopedLock const&) = delete; - GenericScopedLock& operator= (GenericScopedLock const&) = delete; - - /** Destructor. - The lock will be released when the destructor is called. - Make sure this object is created and deleted by the same thread, otherwise there are - no guarantees what will happen! - */ - inline ~GenericScopedLock() noexcept - { - lock_.exit(); - } - -private: - //============================================================================== - const LockType& lock_; -}; - -//============================================================================== -/** - Automatically unlocks and re-locks a mutex object. - - This is the reverse of a GenericScopedLock object - instead of locking the mutex - for the lifetime of this object, it unlocks it. - - Make sure you don't try to unlock mutexes that aren't actually locked! - - e.g. @code - - CriticalSection myCriticalSection; - - for (;;) - { - const GenericScopedLock myScopedLock (myCriticalSection); - // myCriticalSection is now locked - - ... do some stuff with it locked .. - - while (xyz) - { - ... do some stuff with it locked .. - - const GenericScopedUnlock unlocker (myCriticalSection); - - // myCriticalSection is now unlocked for the remainder of this block, - // and re-locked at the end. - - ...do some stuff with it unlocked ... - } - - // myCriticalSection gets unlocked here. - } - @endcode - - @see GenericScopedLock, CriticalSection, ScopedLock, ScopedUnlock -*/ -template -class GenericScopedUnlock -{ -public: - //============================================================================== - /** Creates a GenericScopedUnlock. - - As soon as it is created, this will unlock the CriticalSection, and - when the ScopedLock object is deleted, the CriticalSection will - be re-locked. - - Make sure this object is created and deleted by the same thread, - otherwise there are no guarantees what will happen! Best just to use it - as a local stack object, rather than creating one with the new() operator. - */ - inline explicit GenericScopedUnlock (LockType& lock) noexcept - : lock_ (lock) - { - lock.unlock(); - } - - GenericScopedUnlock (GenericScopedUnlock const&) = delete; - GenericScopedUnlock& operator= (GenericScopedUnlock const&) = delete; - - /** Destructor. - - The CriticalSection will be unlocked when the destructor is called. - - Make sure this object is created and deleted by the same thread, - otherwise there are no guarantees what will happen! - */ - inline ~GenericScopedUnlock() noexcept - { - lock_.lock(); - } - - -private: - //============================================================================== - LockType& lock_; -}; - -//============================================================================== -/** - Automatically locks and unlocks a mutex object. - - Use one of these as a local variable to provide RAII-based locking of a mutex. - - The templated class could be a CriticalSection, SpinLock, or anything else that - provides enter() and exit() methods. - - e.g. @code - - CriticalSection myCriticalSection; - - for (;;) - { - const GenericScopedTryLock myScopedTryLock (myCriticalSection); - - // Unlike using a ScopedLock, this may fail to actually get the lock, so you - // should test this with the isLocked() method before doing your thread-unsafe - // action.. - if (myScopedTryLock.isLocked()) - { - ...do some stuff... - } - else - { - ..our attempt at locking failed because another thread had already locked it.. - } - - // myCriticalSection gets unlocked here (if it was locked) - } - @endcode - - @see CriticalSection::tryEnter, GenericScopedLock, GenericScopedUnlock -*/ -template -class GenericScopedTryLock -{ -public: - //============================================================================== - /** Creates a GenericScopedTryLock. - - As soon as it is created, this will attempt to acquire the lock, and when the - GenericScopedTryLock is deleted, the lock will be released (if the lock was - successfully acquired). - - Make sure this object is created and deleted by the same thread, - otherwise there are no guarantees what will happen! Best just to use it - as a local stack object, rather than creating one with the new() operator. - */ - inline explicit GenericScopedTryLock (const LockType& lock) noexcept - : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {} - - GenericScopedTryLock (GenericScopedTryLock const&) = delete; - GenericScopedTryLock& operator= (GenericScopedTryLock const&) = delete; - - /** Destructor. - - The mutex will be unlocked (if it had been successfully locked) when the - destructor is called. - - Make sure this object is created and deleted by the same thread, - otherwise there are no guarantees what will happen! - */ - inline ~GenericScopedTryLock() noexcept - { - if (lockWasSuccessful) - lock_.exit(); - } - - /** Returns true if the mutex was successfully locked. */ - bool isLocked() const noexcept - { - return lockWasSuccessful; - } - -private: - //============================================================================== - const LockType& lock_; - const bool lockWasSuccessful; -}; - -} // beast - -#endif - diff --git a/beast/module/core/time/Time.cpp b/beast/module/core/time/Time.cpp deleted file mode 100644 index d43cf0d5c1..0000000000 --- a/beast/module/core/time/Time.cpp +++ /dev/null @@ -1,46 +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. -*/ -//============================================================================== - -#include - -namespace beast -{ - -std::int64_t currentTimeMillis() -{ - #if BEAST_WINDOWS - struct _timeb t; - #ifdef _INC_TIME_INL - _ftime_s (&t); - #else - _ftime (&t); - #endif - return ((std::int64_t) t.time) * 1000 + t.millitm; - #else - struct timeval tv; - gettimeofday (&tv, nullptr); - return ((std::int64_t) tv.tv_sec) * 1000 + tv.tv_usec / 1000; - #endif -} - -} // beast diff --git a/beast/module/core/time/Time.h b/beast/module/core/time/Time.h deleted file mode 100644 index 95b1b33d7d..0000000000 --- a/beast/module/core/time/Time.h +++ /dev/null @@ -1,35 +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_MODULE_CORE_TIME_TIME_H_INCLUDED -#define BEAST_MODULE_CORE_TIME_TIME_H_INCLUDED - -#include - -namespace beast { - -std::int64_t currentTimeMillis(); - -} // beast - -#endif // BEAST_TIME_H_INCLUDED diff --git a/beast/net/IPAddress.h b/beast/net/IPAddress.h deleted file mode 100644 index fddd7d6cd0..0000000000 --- a/beast/net/IPAddress.h +++ /dev/null @@ -1,358 +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_NET_IPADDRESS_H_INCLUDED -#define BEAST_NET_IPADDRESS_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//------------------------------------------------------------------------------ - -namespace beast { -namespace IP { - -/** A version-independent IP address. - This object can represent either an IPv4 or IPv6 address. -*/ -class Address -{ -public: - /** Create an unspecified IPv4 address. */ - Address () - : m_type (ipv4) - { - } - - /** Create an IPv4 address. */ - Address (AddressV4 const& addr) - : m_type (ipv4) - , m_v4 (addr) - { - } - - /** Create an IPv6 address. */ - Address (AddressV6 const& addr) - : m_type (ipv6) - , m_v6 (addr) - { - } - - /** Assign a copy from another address in any format. */ - /** @{ */ - Address& - operator= (AddressV4 const& addr) - { - m_type = ipv4; - m_v6 = AddressV6(); - m_v4 = addr; - return *this; - } - - Address& - operator= (AddressV6 const& addr) - { - m_type = ipv6; - m_v4 = AddressV4(); - m_v6 = addr; - return *this; - } - /** @} */ - - /** Create an Address from a string. - @return A pair with the address, and bool set to `true` on success. - */ - static - std::pair - from_string (std::string const& s); - - /** Returns a string representing the address. */ - std::string - to_string () const - { - return (is_v4 ()) - ? IP::to_string (to_v4()) - : IP::to_string (to_v6()); - } - - /** Returns `true` if this address represents an IPv4 address. */ - bool - is_v4 () const noexcept - { - return m_type == ipv4; - } - - /** Returns `true` if this address represents an IPv6 address. */ - bool - is_v6() const noexcept - { - return m_type == ipv6; - } - - /** Returns the IPv4 address. - Precondition: - is_v4() == `true` - */ - AddressV4 const& - to_v4 () const - { - if (!is_v4 ()) - throw std::bad_cast(); - return m_v4; - } - - /** Returns the IPv6 address. - Precondition: - is_v6() == `true` - */ - AddressV6 const& - to_v6 () const - { - if (!is_v6 ()) - throw std::bad_cast(); - return m_v6; - } - - /** Returns `true` if this address represents 0.0.0.0 */ - bool - is_any () const - { - return is_v4 () ? m_v4 == IP::AddressV4::any () - : false; // m_v6 == IP::AddressV6::any(); - } - - template - friend - void - hash_append(Hasher& h, Address const& addr) noexcept - { - using beast::hash_append; - if (addr.is_v4 ()) - hash_append(h, addr.to_v4 ()); - else if (addr.is_v6 ()) - hash_append(h, addr.to_v6 ()); - else - assert (false); - } - - /** Arithmetic comparison. */ - /** @{ */ - friend - bool - operator== (Address const& lhs, Address const& rhs) - { - if (lhs.is_v4 ()) - { - if (rhs.is_v4 ()) - return lhs.to_v4() == rhs.to_v4(); - } - else - { - if (rhs.is_v6 ()) - return lhs.to_v6() == rhs.to_v6(); - } - - return false; - } - - friend - bool - operator< (Address const& lhs, Address const& rhs) - { - if (lhs.m_type < rhs.m_type) - return true; - if (lhs.is_v4 ()) - return lhs.to_v4() < rhs.to_v4(); - return lhs.to_v6() < rhs.to_v6(); - } - - friend - bool - operator!= (Address const& lhs, Address const& rhs) - { - return ! (lhs == rhs); - } - - friend - bool - operator> (Address const& lhs, Address const& rhs) - { - return rhs < lhs; - } - - friend - bool - operator<= (Address const& lhs, Address const& rhs) - { - return ! (lhs > rhs); - } - - friend - bool - operator>= (Address const& lhs, Address const& rhs) - { - return ! (rhs > lhs); - } - /** @} */ - -private: - enum Type - { - ipv4, - ipv6 - }; - - Type m_type; - AddressV4 m_v4; - AddressV6 m_v6; -}; - -//------------------------------------------------------------------------------ - -// Properties - -/** Returns `true` if this is a loopback address. */ -inline -bool -is_loopback (Address const& addr) -{ - return (addr.is_v4 ()) - ? is_loopback (addr.to_v4 ()) - : is_loopback (addr.to_v6 ()); -} - -/** Returns `true` if the address is unspecified. */ -inline -bool -is_unspecified (Address const& addr) -{ - return (addr.is_v4 ()) - ? is_unspecified (addr.to_v4 ()) - : is_unspecified (addr.to_v6 ()); -} - -/** Returns `true` if the address is a multicast address. */ -inline -bool -is_multicast (Address const& addr) -{ - return (addr.is_v4 ()) - ? is_multicast (addr.to_v4 ()) - : is_multicast (addr.to_v6 ()); -} - -/** Returns `true` if the address is a private unroutable address. */ -inline -bool -is_private (Address const& addr) -{ - return (addr.is_v4 ()) - ? is_private (addr.to_v4 ()) - : is_private (addr.to_v6 ()); -} - -/** Returns `true` if the address is a public routable address. */ -inline -bool -is_public (Address const& addr) -{ - return (addr.is_v4 ()) - ? is_public (addr.to_v4 ()) - : is_public (addr.to_v6 ()); -} - -//------------------------------------------------------------------------------ - -/** Returns the address represented as a string. */ -inline std::string to_string (Address const& addr) -{ - return addr.to_string (); -} - -/** Output stream conversion. */ -template -OutputStream& -operator<< (OutputStream& os, Address const& addr) -{ - return os << to_string (addr); -} - -/** Input stream conversion. */ -inline -std::istream& -operator>> (std::istream& is, Address& addr) -{ - // VFALCO TODO Support ipv6! - AddressV4 addrv4; - is >> addrv4; - addr = Address (addrv4); - return is; -} - -inline -std::pair -Address::from_string (std::string const& s) -{ - std::stringstream is (s); - Address addr; - is >> addr; - if (! is.fail() && is.rdbuf()->in_avail() == 0) - return std::make_pair (addr, true); - return std::make_pair (Address (), false); -} - -} -} - -//------------------------------------------------------------------------------ - -namespace std { -template <> -struct hash -{ - std::size_t - operator() (beast::IP::Address const& addr) const - { - return beast::uhash<>{} (addr); - } -}; -} - -namespace boost { -template <> -struct hash -{ - std::size_t - operator() (beast::IP::Address const& addr) const - { - return beast::uhash<>{} (addr); - } -}; -} - -#endif diff --git a/beast/net/IPAddressV4.h b/beast/net/IPAddressV4.h deleted file mode 100644 index 24c9e41c54..0000000000 --- a/beast/net/IPAddressV4.h +++ /dev/null @@ -1,201 +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_NET_IPADDRESSV4_H_INCLUDED -#define BEAST_NET_IPADDRESSV4_H_INCLUDED - -#include - -#include -#include -#include -#include -#include - -namespace beast { -namespace IP { - -/** Represents a version 4 IP address. */ -struct AddressV4 -{ - /** Default constructor represents the 'any' address. */ - AddressV4 (); - - /** Construct from a 32-bit unsigned. - @note Octets are formed in order from the MSB to the LSB. - */ - explicit AddressV4 (std::uint32_t value_); - - /** Construct from four individual octets.. - @note The resulting address is a.b.c.d - */ - AddressV4 (std::uint8_t a, std::uint8_t b, std::uint8_t c, std::uint8_t d); - - /** Create an address from an IPv4 address string in dotted decimal form. - @return A pair with the address, and bool set to `true` on success. - */ - static std::pair from_string (std::string const& s); - - /** Returns an address that represents 'any' address. */ - static AddressV4 any () - { return AddressV4(); } - - /** Returns an address that represents the loopback address. */ - static AddressV4 loopback () - { return AddressV4 (0x7f000001); } - - /** Returns an address that represents the broadcast address. */ - static AddressV4 broadcast () - { return AddressV4 (0xffffffff); } - - /** Returns the broadcast address for the specified address. */ - static AddressV4 broadcast (AddressV4 const& address); - - /** Returns the broadcast address corresponding to the address and mask. */ - static AddressV4 broadcast ( - AddressV4 const& address, AddressV4 const& mask); - - /** Returns `true` if this is a broadcast address. */ - bool is_broadcast () const - { return *this == broadcast (*this); } - - /** Returns the address class for the given address. - @note Class 'D' represents multicast addresses (224.*.*.*). - */ - static char get_class (AddressV4 const& address); - - /** Returns the netmask for the address class or address. */ - /** @{ */ - static AddressV4 netmask (char address_class); - static AddressV4 netmask (AddressV4 const& v); - /** @} */ - - /** Arithmetic comparison. */ - /** @{ */ - friend bool operator== (AddressV4 const& lhs, AddressV4 const& rhs) - { return lhs.value == rhs.value; } - friend bool operator< (AddressV4 const& lhs, AddressV4 const& rhs) - { return lhs.value < rhs.value; } - - friend bool operator!= (AddressV4 const& lhs, AddressV4 const& rhs) - { return ! (lhs == rhs); } - friend bool operator> (AddressV4 const& lhs, AddressV4 const& rhs) - { return rhs < lhs; } - friend bool operator<= (AddressV4 const& lhs, AddressV4 const& rhs) - { return ! (lhs > rhs); } - friend bool operator>= (AddressV4 const& lhs, AddressV4 const& rhs) - { return ! (rhs > lhs); } - /** @} */ - - /** Array indexing for reading and writing indiviual octets. */ - /** @{ */ - template - class Proxy - { - public: - using Pointer = typename std::conditional < - IsConst, std::uint32_t const*, std::uint32_t*>::type; - - Proxy (int shift, Pointer value) - : m_shift (shift) - , m_value (value) - { - } - - operator std::uint8_t() const - { - return ((*m_value)>>m_shift) & 0xff; - } - - template - Proxy& operator= (IntegralType v) - { - (*m_value) = - ( (*m_value) & (~((0xff)< operator[] (std::size_t index) const; - Proxy operator[] (std::size_t index); - /** @} */ - - /** The value as a 32 bit unsigned. */ - std::uint32_t value; -}; - -//------------------------------------------------------------------------------ - -/** Returns `true` if this is a loopback address. */ -bool is_loopback (AddressV4 const& addr); - -/** Returns `true` if the address is unspecified. */ -bool is_unspecified (AddressV4 const& addr); - -/** Returns `true` if the address is a multicast address. */ -bool is_multicast (AddressV4 const& addr); - -/** Returns `true` if the address is a private unroutable address. */ -bool is_private (AddressV4 const& addr); - -/** Returns `true` if the address is a public routable address. */ -bool is_public (AddressV4 const& addr); - -//------------------------------------------------------------------------------ - -/** Returns the address represented as a string. */ -std::string to_string (AddressV4 const& addr); - -/** Output stream conversion. */ -template -OutputStream& operator<< (OutputStream& os, AddressV4 const& addr) - { return os << to_string (addr); } - -/** Input stream conversion. */ -std::istream& operator>> (std::istream& is, AddressV4& addr); - -} - -template -struct is_contiguously_hashable - : public std::integral_constant -{ -}; - -} - -//------------------------------------------------------------------------------ - -namespace std { -/** std::hash support. */ -template <> -struct hash -{ - std::size_t operator() (beast::IP::AddressV4 const& addr) const - { return addr.value; } -}; -} - -#endif diff --git a/beast/net/IPAddressV6.h b/beast/net/IPAddressV6.h deleted file mode 100644 index 98d3377fd9..0000000000 --- a/beast/net/IPAddressV6.h +++ /dev/null @@ -1,108 +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_NET_IPADDRESSV6_H_INCLUDED -#define BEAST_NET_IPADDRESSV6_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace IP { - -/** Represents a version 4 IP address. */ -struct AddressV6 -{ - // VFALCO TODO - - /** Arithmetic comparison. */ - /** @{ */ - friend bool operator== (AddressV6 const&, AddressV6 const&) - { assert(false); return false; } - friend bool operator< (AddressV6 const&, AddressV6 const&) - { assert(false); return false; } - - friend bool operator!= (AddressV6 const& lhs, AddressV6 const& rhs) - { return ! (lhs == rhs); } - friend bool operator> (AddressV6 const& lhs, AddressV6 const& rhs) - { return rhs < lhs; } - friend bool operator<= (AddressV6 const& lhs, AddressV6 const& rhs) - { return ! (lhs > rhs); } - friend bool operator>= (AddressV6 const& lhs, AddressV6 const& rhs) - { return ! (rhs > lhs); } - /** @} */ -}; - -//------------------------------------------------------------------------------ - -/** Returns `true` if this is a loopback address. */ -bool is_loopback (AddressV6 const& addr); - -/** Returns `true` if the address is unspecified. */ -bool is_unspecified (AddressV6 const& addr); - -/** Returns `true` if the address is a multicast address. */ -bool is_multicast (AddressV6 const& addr); - -/** Returns `true` if the address is a private unroutable address. */ -bool is_private (AddressV6 const& addr); - -/** Returns `true` if the address is a public routable address. */ -bool is_public (AddressV6 const& addr); - -//------------------------------------------------------------------------------ - -template -void -hash_append(Hasher&, AddressV6 const&) -{ - assert(false); -} - -/** Returns the address represented as a string. */ -std::string to_string (AddressV6 const& addr); - -/** Output stream conversion. */ -template -OutputStream& operator<< (OutputStream& os, AddressV6 const& addr) - { return os << to_string (addr); } - -/** Input stream conversion. */ -std::istream& operator>> (std::istream& is, AddressV6& addr); - -} -} - -//------------------------------------------------------------------------------ - -namespace std { -/** std::hash support. */ -template <> -struct hash -{ - std::size_t operator() (beast::IP::AddressV6 const& addr) const - { assert(false); return 0; } -}; -} - -#endif diff --git a/beast/net/IPEndpoint.h b/beast/net/IPEndpoint.h deleted file mode 100644 index 6e3961a3c1..0000000000 --- a/beast/net/IPEndpoint.h +++ /dev/null @@ -1,175 +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_NET_IPENDPOINT_H_INCLUDED -#define BEAST_NET_IPENDPOINT_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace IP { - -using Port = std::uint16_t; - -/** A version-independent IP address and port combination. */ -class Endpoint -{ -public: - /** Create an unspecified endpoint. */ - Endpoint (); - - /** Create an endpoint from the address and optional port. */ - explicit Endpoint (Address const& addr, Port port = 0); - - /** Create an Endpoint from a string. - If the port is omitted, the endpoint will have a zero port. - @return A pair with the endpoint, and bool set to `true` on success. - */ - static std::pair from_string_checked (std::string const& s); - static Endpoint from_string (std::string const& s); - static Endpoint from_string_altform (std::string const& s); - - /** Returns a string representing the endpoint. */ - std::string to_string () const; - - /** Returns the port number on the endpoint. */ - Port port () const - { return m_port; } - - /** Returns a new Endpoint with a different port. */ - Endpoint at_port (Port port) const - { return Endpoint (m_addr, port); } - - /** Returns the address portion of this endpoint. */ - Address const& address () const - { return m_addr; } - - /** Convenience accessors for the address part. */ - /** @{ */ - bool is_v4 () const - { return m_addr.is_v4(); } - bool is_v6 () const - { return m_addr.is_v6(); } - AddressV4 const& to_v4 () const - { return m_addr.to_v4 (); } - AddressV6 const& to_v6 () const - { return m_addr.to_v6 (); } - /** @} */ - - /** Arithmetic comparison. */ - /** @{ */ - friend bool operator== (Endpoint const& lhs, Endpoint const& rhs); - friend bool operator< (Endpoint const& lhs, Endpoint const& rhs); - - friend bool operator!= (Endpoint const& lhs, Endpoint const& rhs) - { return ! (lhs == rhs); } - friend bool operator> (Endpoint const& lhs, Endpoint const& rhs) - { return rhs < lhs; } - friend bool operator<= (Endpoint const& lhs, Endpoint const& rhs) - { return ! (lhs > rhs); } - friend bool operator>= (Endpoint const& lhs, Endpoint const& rhs) - { return ! (rhs > lhs); } - /** @} */ - - template - friend - void - hash_append (Hasher& h, Endpoint const& endpoint) - { - using beast::hash_append; - hash_append(h, endpoint.m_addr, endpoint.m_port); - } - -private: - Address m_addr; - Port m_port; -}; - -//------------------------------------------------------------------------------ - -// Properties - -/** Returns `true` if the endpoint is a loopback address. */ -inline bool is_loopback (Endpoint const& endpoint) - { return is_loopback (endpoint.address ()); } - -/** Returns `true` if the endpoint is unspecified. */ -inline bool is_unspecified (Endpoint const& endpoint) - { return is_unspecified (endpoint.address ()); } - -/** Returns `true` if the endpoint is a multicast address. */ -inline bool is_multicast (Endpoint const& endpoint) - { return is_multicast (endpoint.address ()); } - -/** Returns `true` if the endpoint is a private unroutable address. */ -inline bool is_private (Endpoint const& endpoint) - { return is_private (endpoint.address ()); } - -/** Returns `true` if the endpoint is a public routable address. */ -inline bool is_public (Endpoint const& endpoint) - { return is_public (endpoint.address ()); } - -//------------------------------------------------------------------------------ - -/** Returns the endpoint represented as a string. */ -inline std::string to_string (Endpoint const& endpoint) - { return endpoint.to_string(); } - -/** Output stream conversion. */ -template -OutputStream& operator<< (OutputStream& os, Endpoint const& endpoint) -{ - os << to_string (endpoint); - return os; -} - -/** Input stream conversion. */ -std::istream& operator>> (std::istream& is, Endpoint& endpoint); - -} -} - -//------------------------------------------------------------------------------ - -namespace std { -/** std::hash support. */ -template <> -struct hash -{ - std::size_t operator() (beast::IP::Endpoint const& endpoint) const - { return beast::uhash<>{} (endpoint); } -}; -} - -namespace boost { -/** boost::hash support. */ -template <> -struct hash -{ - std::size_t operator() (beast::IP::Endpoint const& endpoint) const - { return beast::uhash<>{} (endpoint); } -}; -} - -#endif diff --git a/beast/net/Net.unity.cpp b/beast/net/Net.unity.cpp deleted file mode 100644 index f9d1cf69d2..0000000000 --- a/beast/net/Net.unity.cpp +++ /dev/null @@ -1,26 +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 - -#include -#include -#include - -#include diff --git a/beast/net/detail/Parse.h b/beast/net/detail/Parse.h deleted file mode 100644 index b3ec58c710..0000000000 --- a/beast/net/detail/Parse.h +++ /dev/null @@ -1,103 +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_NET_DETAIL_PARSE_H_INCLUDED -#define BEAST_NET_DETAIL_PARSE_H_INCLUDED - -#include -#include - -namespace beast { -namespace IP { - -namespace detail { - -/** Require and consume the specified character from the input. - @return `true` if the character matched. -*/ -template -bool expect (InputStream& is, char v) -{ - char c; - if (is.get(c) && v == c) - return true; - is.unget(); - is.setstate (std::ios_base::failbit); - return false; -} - -/** Require and consume whitespace from the input. - @return `true` if the character matched. -*/ -template -bool expect_whitespace (InputStream& is) -{ - char c; - if (is.get(c) && isspace(c)) - return true; - is.unget(); - is.setstate (std::ios_base::failbit); - return false; -} - -/** Used to disambiguate 8-bit integers from characters. */ -template -struct integer_holder -{ - IntType* pi; - explicit integer_holder (IntType& i) - : pi (&i) - { - } - template - IntType& operator= (OtherIntType o) const - { - *pi = o; - return *pi; - } -}; - -/** Parse 8-bit unsigned integer. */ -template -InputStream& operator>> (InputStream& is, integer_holder const& i) -{ - std::uint16_t v; - is >> v; - if (! (v>=0 && v<=255)) - { - is.setstate (std::ios_base::failbit); - return is; - } - i = std::uint8_t(v); - return is; -} - -/** Free function for template argument deduction. */ -template -integer_holder integer (IntType& i) -{ - return integer_holder (i); -} - -} - -} -} - -#endif diff --git a/beast/net/impl/IPAddressV4.cpp b/beast/net/impl/IPAddressV4.cpp deleted file mode 100644 index 223445fb3c..0000000000 --- a/beast/net/impl/IPAddressV4.cpp +++ /dev/null @@ -1,184 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include "../../BeastConfig.h" -#endif - -#include -#include - -#include -#include - -namespace beast { -namespace IP { - -AddressV4::AddressV4 () - : value (0) -{ -} - -AddressV4::AddressV4 (std::uint32_t value_) - : value (value_) -{ -} - -AddressV4::AddressV4 (std::uint8_t a, std::uint8_t b, std::uint8_t c, std::uint8_t d) - : value ((a<<24)|(b<<16)|(c<<8)|d) -{ -} - -std::pair AddressV4::from_string (std::string const& s) -{ - std::stringstream is (s); - AddressV4 addr; - is >> addr; - if (! is.fail() && is.rdbuf()->in_avail() == 0) - return std::make_pair (addr, true); - return std::make_pair (AddressV4 (), false); -} - -AddressV4 AddressV4::broadcast (AddressV4 const& address) -{ - return broadcast (address, netmask (address)); -} - -AddressV4 AddressV4::broadcast ( - AddressV4 const& address, AddressV4 const& mask) -{ - return AddressV4 (address.value | (mask.value ^ 0xffffffff)); -} - -char AddressV4::get_class (AddressV4 const& addr) -{ - static char const* table = "AAAABBCD"; - return table [(addr.value & 0xE0000000) >> 29]; -} - -AddressV4 AddressV4::netmask (char address_class) -{ - switch (address_class) - { - case 'A': return AddressV4 (0xff000000); - case 'B': return AddressV4 (0xffff0000); - case 'C': return AddressV4 (0xffffff00); - case 'D': - default: - break; - } - return AddressV4 (0xffffffff); -} - -AddressV4 AddressV4::netmask (AddressV4 const& addr) -{ - return netmask (get_class (addr)); -} - -AddressV4::Proxy AddressV4::operator[] (std::size_t index) const -{ - switch (index) - { - default: - throw std::out_of_range ("bad array index"); - case 0: return Proxy (24, &value); - case 1: return Proxy (16, &value); - case 2: return Proxy ( 8, &value); - case 3: return Proxy ( 0, &value); - }; -}; - -AddressV4::Proxy AddressV4::operator[] (std::size_t index) -{ - switch (index) - { - default: - throw std::out_of_range ("bad array index"); - case 0: return Proxy (24, &value); - case 1: return Proxy (16, &value); - case 2: return Proxy ( 8, &value); - case 3: return Proxy ( 0, &value); - }; -}; - -//------------------------------------------------------------------------------ - -bool is_loopback (AddressV4 const& addr) -{ - return (addr.value & 0xff000000) == 0x7f000000; -} - -bool is_unspecified (AddressV4 const& addr) -{ - return addr.value == 0; -} - -bool is_multicast (AddressV4 const& addr) -{ - return (addr.value & 0xf0000000) == 0xe0000000; -} - -bool is_private (AddressV4 const& addr) -{ - return - ((addr.value & 0xff000000) == 0x0a000000) || // Prefix /8, 10. #.#.# - ((addr.value & 0xfff00000) == 0xac100000) || // Prefix /12 172. 16.#.# - 172.31.#.# - ((addr.value & 0xffff0000) == 0xc0a80000) || // Prefix /16 192.168.#.# - is_loopback (addr); -} - -bool is_public (AddressV4 const& addr) -{ - return - ! is_private (addr) && - ! is_multicast (addr); -} - -//------------------------------------------------------------------------------ - -std::string to_string (AddressV4 const& addr) -{ - std::string s; - s.reserve (15); - s = - std::to_string (addr[0]) + "." + - std::to_string (addr[1]) + "." + - std::to_string (addr[2]) + "." + - std::to_string (addr[3]); - return s; -} - -std::istream& operator>> (std::istream& is, AddressV4& addr) -{ - std::uint8_t octet [4]; - is >> IP::detail::integer (octet [0]); - for (int i = 1; i < 4; ++i) - { - if (!is || !IP::detail::expect (is, '.')) - return is; - is >> IP::detail::integer (octet [i]); - if (!is) - return is; - } - addr = AddressV4 (octet[0], octet[1], octet[2], octet[3]); - return is; -} - -} -} diff --git a/beast/net/impl/IPAddressV6.cpp b/beast/net/impl/IPAddressV6.cpp deleted file mode 100644 index 62f72b9f1f..0000000000 --- a/beast/net/impl/IPAddressV6.cpp +++ /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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include "../../BeastConfig.h" -#endif - -#include - -namespace beast { -namespace IP { - -//------------------------------------------------------------------------------ - -bool is_loopback (AddressV6 const&) -{ - // VFALCO TODO - assert(false); - return false; -} - -bool is_unspecified (AddressV6 const&) -{ - // VFALCO TODO - assert(false); - return false; -} - -bool is_multicast (AddressV6 const&) -{ - // VFALCO TODO - assert(false); - return false; -} - -bool is_private (AddressV6 const&) -{ - // VFALCO TODO - assert(false); - return false; -} - -bool is_public (AddressV6 const&) -{ - // VFALCO TODO - assert(false); - return false; -} - -//------------------------------------------------------------------------------ - -std::string to_string (AddressV6 const&) -{ - // VFALCO TODO - assert(false); - return ""; -} - -std::istream& operator>> (std::istream& is, AddressV6&) -{ - // VFALCO TODO - assert(false); - return is; -} - -} -} diff --git a/beast/net/impl/IPEndpoint.cpp b/beast/net/impl/IPEndpoint.cpp deleted file mode 100644 index ed15f40823..0000000000 --- a/beast/net/impl/IPEndpoint.cpp +++ /dev/null @@ -1,174 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include "../../BeastConfig.h" -#endif - -#include -#include - -namespace beast { -namespace IP { - -Endpoint::Endpoint () - : m_port (0) -{ -} - -Endpoint::Endpoint (Address const& addr, Port port) - : m_addr (addr) - , m_port (port) -{ -} - -std::pair Endpoint::from_string_checked (std::string const& s) -{ - std::stringstream is (s); - Endpoint endpoint; - is >> endpoint; - if (! is.fail() && is.rdbuf()->in_avail() == 0) - return std::make_pair (endpoint, true); - return std::make_pair (Endpoint (), false); -} - -Endpoint Endpoint::from_string (std::string const& s) -{ - std::pair const result ( - from_string_checked (s)); - if (result.second) - return result.first; - return Endpoint(); -} - -// VFALCO NOTE This is a hack to support legacy data format -// -Endpoint Endpoint::from_string_altform (std::string const& s) -{ - // Accept the regular form if it parses - { - Endpoint ep (Endpoint::from_string (s)); - if (! is_unspecified (ep)) - return ep; - } - - // Now try the alt form - std::stringstream is (s); - - AddressV4 v4; - is >> v4; - if (! is.fail()) - { - Endpoint ep (v4); - - if (is.rdbuf()->in_avail()>0) - { - if (! IP::detail::expect_whitespace (is)) - return Endpoint(); - - while (is.rdbuf()->in_avail()>0) - { - char c; - is.get(c); - if (!isspace (c)) - { - is.unget(); - break; - } - } - - Port port; - is >> port; - if (is.fail()) - return Endpoint(); - - return ep.at_port (port); - } - else - { - // Just an address with no port - return ep; - } - } - - // Could be V6 here... - - return Endpoint(); -} - -std::string Endpoint::to_string () const -{ - std::string s (address ().to_string ()); - if (port() != 0) - s = s + ":" + std::to_string (port()); - return s; -} - -bool operator== (Endpoint const& lhs, Endpoint const& rhs) -{ - return lhs.address() == rhs.address() && - lhs.port() == rhs.port(); -} - -bool operator< (Endpoint const& lhs, Endpoint const& rhs) -{ - if (lhs.address() < rhs.address()) - return true; - if (lhs.address() > rhs.address()) - return false; - return lhs.port() < rhs.port(); -} - -//------------------------------------------------------------------------------ - -std::istream& operator>> (std::istream& is, Endpoint& endpoint) -{ - // VFALCO TODO Support ipv6! - - Address addr; - is >> addr; - if (is.fail()) - return is; - - if (is.rdbuf()->in_avail()>0) - { - char c; - is.get(c); - if (c != ':') - { - is.unget(); - endpoint = Endpoint (addr); - return is; - } - - Port port; - is >> port; - if (is.fail()) - return is; - - endpoint = Endpoint (addr, port); - return is; - } - - endpoint = Endpoint (addr); - return is; -} - -} -} diff --git a/beast/net/tests/IPEndpoint.test.cpp b/beast/net/tests/IPEndpoint.test.cpp deleted file mode 100644 index b10fb314aa..0000000000 --- a/beast/net/tests/IPEndpoint.test.cpp +++ /dev/null @@ -1,354 +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. -*/ -//============================================================================== - -// MODULES: ../impl/IPEndpoint.cpp ../impl/IPAddressV4.cpp ../impl/IPAddressV6.cpp - -#if BEAST_INCLUDE_BEASTCONFIG -#include "../../BeastConfig.h" -#endif - -#include -#include - -#include - -#include - -namespace beast { -namespace IP { - -//------------------------------------------------------------------------------ - -class IPEndpoint_test : public unit_test::suite -{ -public: - void shouldParseV4 (std::string const& s, std::uint32_t value) - { - std::pair const result ( - AddressV4::from_string (s)); - - if (expect (result.second)) - { - if (expect (result.first.value == value)) - { - expect (to_string (result.first) == s); - } - } - } - - void failParseV4 (std::string const& s) - { - unexpected (AddressV4::from_string (s).second); - } - - void testAddressV4 () - { - testcase ("AddressV4"); - - expect (AddressV4().value == 0); - expect (is_unspecified (AddressV4())); - expect (AddressV4(0x01020304).value == 0x01020304); - expect (AddressV4(1, 2, 3, 4).value == 0x01020304); - - unexpected (is_unspecified (AddressV4(1, 2, 3, 4))); - - AddressV4 const v1 (1); - expect (AddressV4(v1).value == 1); - - { - AddressV4 v; - v = v1; - expect (v.value == v1.value); - } - - { - AddressV4 v; - v [0] = 1; - v [1] = 2; - v [2] = 3; - v [3] = 4; - expect (v.value == 0x01020304); - } - - expect (to_string (AddressV4(0x01020304)) == "1.2.3.4"); - - shouldParseV4 ("1.2.3.4", 0x01020304); - shouldParseV4 ("255.255.255.255", 0xffffffff); - shouldParseV4 ("0.0.0.0", 0); - - failParseV4 ("."); - failParseV4 (".."); - failParseV4 ("..."); - failParseV4 ("...."); - failParseV4 ("1"); - failParseV4 ("1."); - failParseV4 ("1.2"); - failParseV4 ("1.2."); - failParseV4 ("1.2.3"); - failParseV4 ("1.2.3."); - failParseV4 ("256.0.0.0"); - failParseV4 ("-1.2.3.4"); - } - - void testAddressV4Proxy () - { - testcase ("AddressV4::Proxy"); - - AddressV4 v4 (10, 0, 0, 1); - expect (v4[0]==10); - expect (v4[1]==0); - expect (v4[2]==0); - expect (v4[3]==1); - - expect((!((0xff)<<16)) == 0x00000000); - expect((~((0xff)<<16)) == 0xff00ffff); - - v4[1] = 10; - expect (v4[0]==10); - expect (v4[1]==10); - expect (v4[2]==0); - expect (v4[3]==1); - } - - //-------------------------------------------------------------------------- - - void testAddress () - { - testcase ("Address"); - - std::pair result ( - Address::from_string ("1.2.3.4")); - expect (result.second); - if (expect (result.first.is_v4 ())) - expect (result.first.to_v4() == AddressV4 (1, 2, 3, 4)); - } - - //-------------------------------------------------------------------------- - - void testEndpoint () - { - testcase ("Endpoint"); - - { - std::pair result ( - Endpoint::from_string_checked ("1.2.3.4")); - expect (result.second); - if (expect (result.first.address().is_v4 ())) - { - expect (result.first.address().to_v4() == - AddressV4 (1, 2, 3, 4)); - expect (result.first.port() == 0); - expect (to_string (result.first) == "1.2.3.4"); - } - } - - { - std::pair result ( - Endpoint::from_string_checked ("1.2.3.4:5")); - expect (result.second); - if (expect (result.first.address().is_v4 ())) - { - expect (result.first.address().to_v4() == - AddressV4 (1, 2, 3, 4)); - expect (result.first.port() == 5); - expect (to_string (result.first) == "1.2.3.4:5"); - } - } - - Endpoint ep; - - ep = Endpoint (AddressV4 (127,0,0,1), 80); - expect (! is_unspecified (ep)); - expect (! is_public (ep)); - expect ( is_private (ep)); - expect (! is_multicast (ep)); - expect ( is_loopback (ep)); - expect (to_string (ep) == "127.0.0.1:80"); - - ep = Endpoint (AddressV4 (10,0,0,1)); - expect (AddressV4::get_class (ep.to_v4()) == 'A'); - expect (! is_unspecified (ep)); - expect (! is_public (ep)); - expect ( is_private (ep)); - expect (! is_multicast (ep)); - expect (! is_loopback (ep)); - expect (to_string (ep) == "10.0.0.1"); - - ep = Endpoint (AddressV4 (166,78,151,147)); - expect (! is_unspecified (ep)); - expect ( is_public (ep)); - expect (! is_private (ep)); - expect (! is_multicast (ep)); - expect (! is_loopback (ep)); - expect (to_string (ep) == "166.78.151.147"); - - { - ep = Endpoint::from_string ("192.0.2.112"); - expect (! is_unspecified (ep)); - expect (ep == Endpoint::from_string_altform ("192.0.2.112")); - - auto const ep1 = Endpoint::from_string ("192.0.2.112:2016"); - expect (! is_unspecified (ep1)); - expect (ep.address() == ep1.address()); - expect (ep1.port() == 2016); - - auto const ep2 = - Endpoint::from_string_altform ("192.0.2.112:2016"); - expect (! is_unspecified (ep2)); - expect (ep.address() == ep2.address()); - expect (ep2.port() == 2016); - expect (ep1 == ep2); - - auto const ep3 = - Endpoint::from_string_altform ("192.0.2.112 2016"); - expect (! is_unspecified (ep3)); - expect (ep.address() == ep3.address()); - expect (ep3.port() == 2016); - expect (ep2 == ep3); - - auto const ep4 = - Endpoint::from_string_altform ("192.0.2.112 2016"); - expect (! is_unspecified (ep4)); - expect (ep.address() == ep4.address()); - expect (ep4.port() == 2016); - expect (ep3 == ep4); - - expect (to_string(ep1) == to_string(ep2)); - expect (to_string(ep1) == to_string(ep3)); - expect (to_string(ep1) == to_string(ep4)); - } - - // Failures: - expect (is_unspecified ( - Endpoint::from_string ("192.0.2.112:port"))); - expect (is_unspecified ( - Endpoint::from_string_altform ("192.0.2.112:port"))); - expect (is_unspecified ( - Endpoint::from_string_altform ("192.0.2.112 port"))); - - expect (is_unspecified ( - Endpoint::from_string ("ip:port"))); - expect (is_unspecified ( - Endpoint::from_string_altform ("ip:port"))); - expect (is_unspecified ( - Endpoint::from_string_altform ("ip port"))); - - expect (is_unspecified ( - Endpoint::from_string(""))); - expect (is_unspecified ( - Endpoint::from_string_altform(""))); - - expect (is_unspecified ( - Endpoint::from_string("255"))); - expect (is_unspecified ( - Endpoint::from_string_altform("255"))); - - expect (is_unspecified ( - Endpoint::from_string("512"))); - expect (is_unspecified ( - Endpoint::from_string_altform("512"))); - - expect (is_unspecified ( - Endpoint::from_string("1.2.3.256"))); - expect (is_unspecified ( - Endpoint::from_string_altform("1.2.3.256"))); - - expect (is_unspecified ( - Endpoint::from_string("1.2.3:80"))); - expect (is_unspecified ( - Endpoint::from_string_altform("1.2.3:80"))); - expect (is_unspecified ( - Endpoint::from_string_altform("1.2.3 80"))); - - expect (is_unspecified ( - Endpoint::from_string("1.2.3.4:65536"))); - expect (is_unspecified ( - Endpoint::from_string_altform("1.2.3:65536"))); - expect (is_unspecified ( - Endpoint::from_string_altform("1.2.3 65536"))); - - expect (is_unspecified ( - Endpoint::from_string("1.2.3.4:89119"))); - expect (is_unspecified ( - Endpoint::from_string_altform("1.2.3:89119"))); - expect (is_unspecified ( - Endpoint::from_string_altform("1.2.3 89119"))); - } - - //-------------------------------------------------------------------------- - - template - bool parse (char const* text, T& t) - { - std::string input (text); - std::istringstream stream (input); - stream >> t; - return !stream.fail(); - } - - template - void shouldPass (char const* text) - { - T t; - expect (parse (text, t)); - expect (to_string (t) == std::string (text)); - } - - template - void shouldFail (char const* text) - { - T t; - unexpected (parse (text, t)); - } - - template - void testParse (char const* name) - { - testcase (name); - - shouldPass ("0.0.0.0"); - shouldPass ("192.168.0.1"); - shouldPass ("168.127.149.132"); - shouldPass ("168.127.149.132:80"); - shouldPass ("168.127.149.132:54321"); - - shouldFail (""); - shouldFail ("255"); - shouldFail ("512"); - shouldFail ("1.2.3.256"); - shouldFail ("1.2.3:80"); - shouldFail ("1.2.3:65536"); - shouldFail ("1.2.3:72131"); - } - - void run () - { - testAddressV4 (); - testAddressV4Proxy(); - testAddress (); - testEndpoint (); - - testParse ("Parse Endpoint"); - } -}; - -BEAST_DEFINE_TESTSUITE(IPEndpoint,net,beast); - -} -} diff --git a/beast/nudb.h b/beast/nudb.h deleted file mode 100644 index e413c336f5..0000000000 --- a/beast/nudb.h +++ /dev/null @@ -1,32 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_H_INCLUDED -#define BEAST_NUDB_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/beast/nudb/README.md b/beast/nudb/README.md deleted file mode 100644 index 054cc33e96..0000000000 --- a/beast/nudb/README.md +++ /dev/null @@ -1,288 +0,0 @@ -# NuDB: A Key/Value Store For Decentralized Systems - -The new breed of decentralized systems such as Ripple or Bitcoin -that use embedded key/value databases place different demands on -these database than what is traditional. NuDB provides highly -optimized and concurrent atomic, durable, and isolated fetch and -insert operations to secondary storage, along with these features: - -* Low memory footprint. -* Values are immutable. -* Value sizes from 1 to 2^48 bytes (281TB). -* All keys are the same size. -* Performance independent of growth. -* Optimized for concurrent fetch. -* Key file can be rebuilt if needed. -* Inserts are atomic and consistent. -* Data files may be efficiently iterated. -* Key and data files may be on different volumes. -* Hardened against algorithmic complexity attacks. -* Header-only, nothing to build or link. - -Three files are used. - -* The data file holds keys and values stored sequentially and size-prefixed. -* The key file holds a series of fixed-size bucket records forming an on-disk - hash table. -* The log file stores bookkeeping information used to restore consistency when -an external failure occurs. - -In typical cases a fetch costs one I/O cycle to consult the key file, and if the -key is present, one I/O cycle to read the value. - -## Usage - -Callers must define these parameters when _creating_ a database: - -* `KeySize`: The size of a key in bytes. -* `BlockSize`: The physical size of a key file record. - -The ideal block size matches the sector size or block size of the -underlying physical media that holds the key file. Functions are -provided to return a best estimate of this value for a particular -device, but a default of 4096 should work for typical installations. -The implementation tries to fit as many entries as possible in a key -file record, to maximize the amount of useful work performed per I/O. - -* `LoadFactor`: The desired fraction of bucket occupancy - -`LoadFactor` is chosen to make bucket overflows unlikely without -sacrificing bucket occupancy. A value of 0.50 seems to work well with -a good hash function. - -Callers must also provide these parameters when a database is _opened:_ - -* `Appnum`: An application-defined integer constant which can be retrieved -later from the database [TODO]. -* `AllocSize`: A significant multiple of the average data size. - -Memory is recycled to improve performance, so NuDB needs `AllocSize` as a -hint about the average size of the data being inserted. For an average data size -of 1KB (one kilobyte), `AllocSize` of sixteen megabytes (16MB) is sufficient. If -the `AllocSize` is too low, the memory recycler will not make efficient use of -allocated blocks. - -Two operations are defined: `fetch`, and `insert`. - -### `fetch` - -The `fetch` operation retrieves a variable length value given the -key. The caller supplies a factory used to provide a buffer for storing -the value. This interface allows custom memory allocation strategies. - -### `insert` - -`insert` adds a key/value pair to the store. Value data must contain at least -one byte. Duplicate keys are disallowed. Insertions are serialized, which means -[TODO]. - -## Implementation - -All insertions are buffered in memory, with inserted values becoming -immediately discoverable in subsequent or concurrent calls to fetch. -Periodically, buffered data is safely committed to disk files using -a separate dedicated thread associated with the database. This commit -process takes place at least once per second, or more often during -a detected surge in insertion activity. In the commit process the -key/value pairs receive the following treatment: - -An insertion is performed by appending a value record to the data file. -The value record has some header information including the size of the -data and a copy of the key; the data file is iteratable without the key -file. The value data follows the header. The data file is append-only -and immutable: once written, bytes are never changed. - -Initially the hash table in the key file consists of a single bucket. -After the load factor is exceeded from insertions, the hash table grows -in size by one bucket by doing a "split". The split operation is the -[linear hashing algorithm](http://en.wikipedia.org/wiki/Linear_hashing) -as described by Litwin and Larson. - - -When a bucket is split, each key is rehashed, and either remains in the -original bucket or gets moved to the a bucket appended to the end of -the key file. - -An insertion on a full bucket first triggers the "spill" algorithm. - -First, a spill record is appended to the data file, containing header -information followed by the entire bucket record. Then the bucket's size is set -to zero and the offset of the spill record is stored in the bucket. At this -point the insertion may proceed normally, since the bucket is empty. Spilled -buckets in the data file are always full. - -Because every bucket holds the offset of the next spill record in the -data file, the buckets form a linked list. In practice, careful -selection of capacity and load factor will keep the percentage of -buckets with one spill record to a minimum, with no bucket requiring -two spill records. - -The implementation of fetch is straightforward: first the bucket in the -key file is checked, then each spill record in the linked list of -spill records is checked, until the key is found or there are no more -records. As almost all buckets have no spill records, the average -fetch requires one I/O (not including reading the value). - -One complication in the scheme is when a split occurs on a bucket that -has one or more spill records. In this case, both the bucket being split -and the new bucket may overflow. This is handled by performing the -spill algorithm for each overflow that occurs. The new buckets may have -one or more spill records each, depending on the number of keys that -were originally present. - -Because the data file is immutable, a bucket's original spill records -are no longer referenced after the bucket is split. These blocks of data -in the data file are unrecoverable wasted space. Correctly configured -databases can have a typical waste factor of 1%, which is acceptable. -These unused bytes can be removed by visiting each value in the value -file using an off-line process and inserting it into a new database, -then delete the old database and use the new one instead. - -## Recovery - -To provide atomicity and consistency, a log file associated with the -database stores information used to roll back partial commits. - -## Iteration - -Each record in the data file is prefixed with a header identifying -whether it is a value record or a spill record, along with the size of -the record in bytes and a copy of the key if it's a value record, so values can -be iterated by incrementing a byte counter. A key file can be regenerated from -just the data file by iterating the values and performing the key -insertion algorithm. - -## Concurrency - -Locks are never held during disk reads and writes. Fetches are fully -concurrent, while inserts are serialized. Inserts fail on duplicate -keys, and are atomic: they either succeed immediately or fail. -After an insert, the key is immediately visible to subsequent fetches. - -## Formats - -All integer values are stored as big endian. The uint48_t format -consists of 6 bytes. - -### Key File - -The Key File contains the Header followed by one or more -fixed-length Bucket Records. - -#### Header (104 bytes) - - char[8] Type The characters "nudb.key" - uint16 Version Holds the version number - uint64 UID Unique ID generated on creation - uint64 Appnum Application defined constant - uint16 KeySize Key size in bytes - - uint64 Salt A random seed - uint64 Pepper The salt hashed - uint16 BlockSize Size of a file block in bytes - - uint16 LoadFactor Target fraction in 65536ths - - uint8[56] Reserved Zeroes - uint8[] Reserved Zero-pad to block size - -`Type` identifies the file as belonging to nudb. `UID` is -generated randomly when the database is created, and this value -is stored in the data and log files as well - it's used -to determine if files belong to the same database. `Salt` is -generated when the database is created and helps prevent -complexity attacks; it is prepended to the key material -when computing a hash, or used to initialize the state of -the hash function. `Appnum` is an application defined constant -set when the database is created. It can be used for anything, -for example to distinguish between different data formats. - -`Pepper` is computed by hashing `Salt` using a hash function -seeded with the salt. This is used to fingerprint the hash -function used. If a database is opened and the fingerprint -does not match the hash calculation performed using the template -argument provided when constructing the store, an exception -is thrown. - -The header for the key file contains the File Header followed by -the information above. The Capacity is the number of keys per -bucket, and defines the size of a bucket record. The load factor -is the target fraction of bucket occupancy. - -None of the information in the key file header or the data file -header may be changed after the database is created, including -the Appnum. - -#### Bucket Record (fixed-length) - - uint16 Count Number of keys in this bucket - uint48 Spill Offset of the next spill record or 0 - BucketEntry[] Entries The bucket entries - -#### Bucket Entry - - uint48 Offset Offset in data file of the data - uint48 Size The size of the value in bytes - uint48 Hash The hash of the key - -### Data File - -The Data File contains the Header followed by zero or more -variable-length Value Records and Spill Records. - -#### Header (92 bytes) - - char[8] Type The characters "nudb.dat" - uint16 Version Holds the version number - uint64 UID Unique ID generated on creation - uint64 Appnum Application defined constant - uint16 KeySize Key size in bytes - uint8[64] (reserved) Zeroes - -UID contains the same value as the salt in the corresponding key -file. This is placed in the data file so that key and value files -belonging to the same database can be identified. - -#### Data Record (variable-length) - - uint48 Size Size of the value in bytes - uint8[KeySize] Key The key. - uint8[Size] Data The value data. - -#### Spill Record (fixed-length) - - uint48 Zero All zero, identifies a spill record - uint16 Size Bytes in spill bucket (for skipping) - Bucket SpillBucket Bucket Record - -### Log File - -The Log file contains the Header followed by zero or more fixed size -log records. Each log record contains a snapshot of a bucket. When a -database is not closed cleanly, the recovery process applies the log -records to the key file, overwriting data that may be only partially -updated with known good information. After the log records are applied, -the data and key files are truncated to the last known good size. - -#### Header (62 bytes) - - char[8] Type The characters "nudb.log" - uint16 Version Holds the version number - uint64 UID Unique ID generated on creation - uint64 Appnum Application defined constant - uint16 KeySize Key size in bytes - - uint64 Salt A random seed. - uint64 Pepper The salt hashed - uint16 BlockSize Size of a file block in bytes - - uint64 KeyFileSize Size of key file. - uint64 DataFileSize Size of data file. - -#### Log Record - - uint64_t Index Bucket index (0-based) - Bucket Bucket Compact Bucket record - -Compact buckets include only Size entries. These are primarily -used to minimize the volume of writes to the log file. diff --git a/beast/nudb/api.h b/beast/nudb/api.h deleted file mode 100644 index a473c62ff8..0000000000 --- a/beast/nudb/api.h +++ /dev/null @@ -1,110 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_API_H_INCLUDED -#define BEAST_NUDB_API_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { - -// Convenience for consolidating template arguments -// -template < - class Hasher, - class Codec = identity, - class File = native_file, - std::size_t BufferSize = 16 * 1024 * 1024 -> -struct api -{ - using hash_type = Hasher; - using codec_type = Codec; - using file_type = File; - using store = nudb::store; - - static std::size_t const buffer_size = BufferSize; - - template - static - bool - create ( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::uint64_t appnum, - std::uint64_t salt, - std::size_t key_size, - std::size_t block_size, - float load_factor, - Args&&... args) - { - return nudb::create( - dat_path, key_path, log_path, - appnum, salt, key_size, block_size, - load_factor, args...); - } - - template - static - bool - recover ( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - Args&&... args) - { - return nudb::recover( - dat_path, key_path, log_path, BufferSize, - args...); - } - - static - verify_info - verify ( - path_type const& dat_path, - path_type const& key_path) - { - return nudb::verify( - dat_path, key_path, BufferSize); - } - - template - static - bool - visit( - path_type const& path, - Function&& f) - { - return nudb::visit( - path, BufferSize, f); - } -}; - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/common.h b/beast/nudb/common.h deleted file mode 100644 index 12a1345874..0000000000 --- a/beast/nudb/common.h +++ /dev/null @@ -1,123 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_COMMON_H_INCLUDED -#define BEAST_NUDB_COMMON_H_INCLUDED - -#include -#include - -namespace beast { -namespace nudb { - -// Commonly used types - -enum class file_mode -{ - scan, // read sequential - read, // read random - append, // read random, write append - write // read random, write random -}; - -using path_type = std::string; - -// All exceptions thrown by nudb are derived -// from std::runtime_error except for fail_error - -/** Thrown when a codec fails, e.g. corrupt data. */ -struct codec_error : std::runtime_error -{ - template - explicit - codec_error (String const& s) - : runtime_error(s) - { - } -}; - -/** Base class for all errors thrown by file classes. */ -struct file_error : std::runtime_error -{ - template - explicit - file_error (String const& s) - : runtime_error(s) - { - } -}; - -/** Thrown when file bytes read are less than requested. */ -struct file_short_read_error : file_error -{ - file_short_read_error() - : file_error ( - "nudb: short read") - { - } -}; - -/** Thrown when file bytes written are less than requested. */ -struct file_short_write_error : file_error -{ - file_short_write_error() - : file_error ( - "nudb: short write") - { - } -}; - -/** Thrown when end of istream reached while reading. */ -struct short_read_error : std::runtime_error -{ - short_read_error() - : std::runtime_error( - "nudb: short read") - { - } -}; - -/** Base class for all exceptions thrown by store. */ -class store_error : public std::runtime_error -{ -public: - template - explicit - store_error (String const& s) - : runtime_error(s) - { - } -}; - -/** Thrown when corruption in a file is detected. */ -class store_corrupt_error : public store_error -{ -public: - template - explicit - store_corrupt_error (String const& s) - : store_error(s) - { - } -}; - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/create.h b/beast/nudb/create.h deleted file mode 100644 index 30f3a700e9..0000000000 --- a/beast/nudb/create.h +++ /dev/null @@ -1,164 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_CREATE_H_INCLUDED -#define BEAST_NUDB_CREATE_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { - -namespace detail { - -template -std::uint64_t -make_uid() -{ - std::random_device rng; - std::mt19937_64 gen {rng()}; - std::uniform_int_distribution dist; - return dist(gen); -} - -} - -/** Generate a random salt. */ -template -std::uint64_t -make_salt() -{ - std::random_device rng; - std::mt19937_64 gen {rng()}; - std::uniform_int_distribution dist; - return dist(gen); -} - -/** Returns the best guess at the volume's block size. */ -inline -std::size_t -block_size (path_type const& /*path*/) -{ - return 4096; -} - -/** Create a new database. - Preconditions: - The files must not exist - Throws: - - @param args Arguments passed to File constructors - @return `false` if any file could not be created. -*/ -template < - class Hasher, - class Codec, - class File, - class... Args -> -bool -create ( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::uint64_t appnum, - std::uint64_t salt, - std::size_t key_size, - std::size_t block_size, - float load_factor, - Args&&... args) -{ - using namespace detail; - if (key_size < 1) - throw std::domain_error( - "invalid key size"); - if (block_size > field::max) - throw std::domain_error( - "nudb: block size too large"); - if (load_factor <= 0.f) - throw std::domain_error( - "nudb: load factor too small"); - if (load_factor >= 1.f) - throw std::domain_error( - "nudb: load factor too large"); - auto const capacity = - bucket_capacity(block_size); - if (capacity < 1) - throw std::domain_error( - "nudb: block size too small"); - File df(args...); - File kf(args...); - File lf(args...); - if (df.create( - file_mode::append, dat_path)) - { - if (kf.create ( - file_mode::append, key_path)) - { - if (lf.create( - file_mode::append, log_path)) - goto success; - File::erase (dat_path); - } - File::erase (key_path); - } - return false; -success: - dat_file_header dh; - dh.version = currentVersion; - dh.uid = make_uid(); - dh.appnum = appnum; - dh.key_size = key_size; - - key_file_header kh; - kh.version = currentVersion; - kh.uid = dh.uid; - kh.appnum = appnum; - kh.key_size = key_size; - kh.salt = salt; - kh.pepper = pepper(salt); - kh.block_size = block_size; - // VFALCO Should it be 65536? - // How do we set the min? - kh.load_factor = std::min( - 65536.0 * load_factor, 65535); - write (df, dh); - write (kf, kh); - buffer buf(block_size); - std::memset(buf.get(), 0, block_size); - bucket b (block_size, buf.get(), empty); - b.write (kf, block_size); - // VFALCO Leave log file empty? - df.sync(); - kf.sync(); - lf.sync(); - return true; -} - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/arena.h b/beast/nudb/detail/arena.h deleted file mode 100644 index fa8059cefd..0000000000 --- a/beast/nudb/detail/arena.h +++ /dev/null @@ -1,246 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_ARENA_H_INCLUDED -#define BEAST_NUDB_DETAIL_ARENA_H_INCLUDED - -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -/* Custom memory manager that allocates in large blocks. - - No limit is placed on the size of an allocation but - alloc_size should be tuned upon construction to be a - significant multiple of the average allocation size. - - When the arena is cleared, allocated memory is placed - on a free list for re-use, avoiding future system calls. -*/ -template -class arena_t -{ -private: - class element; - - std::size_t alloc_size_; - element* used_ = nullptr; - element* free_ = nullptr; - -public: - arena_t (arena_t const&); - arena_t& operator= (arena_t const&); - - ~arena_t(); - - explicit - arena_t (std::size_t alloc_size); - - arena_t& operator= (arena_t&& other); - - // Makes used blocks free - void - clear(); - - // deletes free blocks - void - shrink_to_fit(); - - std::uint8_t* - alloc (std::size_t n); - - template - friend - void - swap (arena_t& lhs, arena_t& rhs); - -private: - void - dealloc (element*& list); -}; - -//------------------------------------------------------------------------------ - -template -class arena_t<_>::element -{ -private: - std::size_t const capacity_; - std::size_t used_ = 0; - -public: - element* next = nullptr; - - explicit - element (std::size_t alloc_size) - : capacity_ ( - alloc_size - sizeof(*this)) - { - } - - void - clear() - { - used_ = 0; - } - - std::size_t - remain() const - { - return capacity_ - used_; - } - - std::size_t - capacity() const - { - return capacity_; - } - - std::uint8_t* - alloc (std::size_t n); -}; - -template -std::uint8_t* -arena_t<_>::element::alloc (std::size_t n) -{ - if (n > capacity_ - used_) - return nullptr; - auto const p = const_cast( - reinterpret_cast(this + 1) - ) + used_; - used_ += n; - return p; -} - -//------------------------------------------------------------------------------ - -template -arena_t<_>::arena_t (std::size_t alloc_size) - : alloc_size_ (alloc_size) -{ - if (alloc_size <= sizeof(element)) - throw std::domain_error( - "arena: bad alloc size"); -} - -template -arena_t<_>::~arena_t() -{ - dealloc (used_); - dealloc (free_); -} - -template -arena_t<_>& -arena_t<_>::operator= (arena_t&& other) -{ - dealloc (used_); - dealloc (free_); - alloc_size_ = other.alloc_size_; - used_ = other.used_; - free_ = other.free_; - other.used_ = nullptr; - other.free_ = nullptr; - return *this; -} - -template -void -arena_t<_>::clear() -{ - while (used_) - { - auto const e = used_; - used_ = used_->next; - e->clear(); - e->next = free_; - free_ = e; - } -} - -template -void -arena_t<_>::shrink_to_fit() -{ - dealloc (free_); -} - -template -std::uint8_t* -arena_t<_>::alloc (std::size_t n) -{ - // Undefined behavior: Zero byte allocations - assert(n != 0); - n = 8 * ((n + 7) / 8); - if (used_ && used_->remain() >= n) - return used_->alloc(n); - if (free_ && free_->remain() >= n) - { - auto const e = free_; - free_ = free_->next; - e->next = used_; - used_ = e; - return used_->alloc(n); - } - std::size_t const size = std::max( - alloc_size_, sizeof(element) + n); - element* const e = reinterpret_cast( - new std::uint8_t[size]); - ::new(e) element(size); - e->next = used_; - used_ = e; - return used_->alloc(n); -} - -template -void -swap (arena_t<_>& lhs, arena_t<_>& rhs) -{ - using std::swap; - swap(lhs.alloc_size_, rhs.alloc_size_); - swap(lhs.used_, rhs.used_); - swap(lhs.free_, rhs.free_); -} - -template -void -arena_t<_>::dealloc (element*& list) -{ - while (list) - { - auto const e = list; - list = list->next; - e->~element(); - delete[] reinterpret_cast(e); - } -} - -using arena = arena_t<>; - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/bucket.h b/beast/nudb/detail/bucket.h deleted file mode 100644 index 097494c57d..0000000000 --- a/beast/nudb/detail/bucket.h +++ /dev/null @@ -1,468 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_BUCKET_H_INCLUDED -#define BEAST_NUDB_DETAIL_BUCKET_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// bucket calculations: - -// Returns bucket index given hash, buckets, and modulus -// -inline -std::size_t -bucket_index (std::size_t h, - std::size_t buckets, std::size_t modulus) -{ - std::size_t n = h % modulus; - if (n >= buckets) - n -= modulus / 2; - return n; -} - -//------------------------------------------------------------------------------ - -// Tag for constructing empty buckets -struct empty_t { }; -static empty_t empty; - -// Allows inspection and manipulation of bucket blobs in memory -template -class bucket_t -{ -private: - std::size_t block_size_; // Size of a key file block - std::size_t size_; // Current key count - std::size_t spill_; // Offset of next spill record or 0 - std::uint8_t* p_; // Pointer to the bucket blob - -public: - struct value_type - { - std::size_t offset; - std::size_t size; - std::size_t hash; - }; - - bucket_t (bucket_t const&) = default; - bucket_t& operator= (bucket_t const&) = default; - - bucket_t (std::size_t block_size, void* p); - - bucket_t (std::size_t block_size, void* p, empty_t); - - std::size_t - block_size() const - { - return block_size_; - } - - std::size_t - compact_size() const - { - return detail::bucket_size(size_); - } - - bool - empty() const - { - return size_ == 0; - } - - bool - full() const - { - return size_ >= - detail::bucket_capacity(block_size_); - } - - std::size_t - size() const - { - return size_; - } - - // Returns offset of next spill record or 0 - // - std::size_t - spill() const - { - return spill_; - } - - // Set offset of next spill record - // - void - spill (std::size_t offset); - - // Clear contents of the bucket - // - void - clear(); - - // Returns the record for a key - // entry without bounds checking. - // - value_type const - at (std::size_t i) const; - - value_type const - operator[] (std::size_t i) const - { - return at(i); - } - - // Returns index of entry with prefix - // equal to or greater than the given prefix. - // - std::size_t - lower_bound (std::size_t h) const; - - void - insert (std::size_t offset, - std::size_t size, std::size_t h); - - // Erase an element by index - // - void - erase (std::size_t i); - - // Read a full bucket from the - // file at the specified offset. - // - template - void - read (File& f, std::size_t offset); - - // Read a compact bucket - // - template - void - read (bulk_reader& r); - - // Write a compact bucket to the stream. - // This only writes entries that are not empty. - // - void - write (ostream& os) const; - - // Write a bucket to the file at the specified offset. - // The full block_size() bytes are written. - // - template - void - write (File& f, std::size_t offset) const; - -private: - // Update size and spill in the blob - void - update(); -}; - -//------------------------------------------------------------------------------ - -template -bucket_t<_>::bucket_t ( - std::size_t block_size, void* p) - : block_size_ (block_size) - , p_ (reinterpret_cast(p)) -{ - // Bucket Record - istream is(p_, block_size); - detail::read(is, size_); // Count - detail::read(is, spill_); // Spill -} - -template -bucket_t<_>::bucket_t ( - std::size_t block_size, void* p, empty_t) - : block_size_ (block_size) - , size_ (0) - , spill_ (0) - , p_ (reinterpret_cast(p)) -{ - clear(); -} - -template -void -bucket_t<_>::spill (std::size_t offset) -{ - spill_ = offset; - update(); -} - -template -void -bucket_t<_>::clear() -{ - size_ = 0; - spill_ = 0; - std::memset(p_, 0, block_size_); -} - -template -auto -bucket_t<_>::at (std::size_t i) const -> - value_type const -{ - value_type result; - // Bucket Entry - std::size_t const w = - field::size + // Offset - field::size + // Size - field::size; // Prefix - // Bucket Record - detail::istream is(p_ + - field::size + // Count - field::size + // Spill - i * w, w); - // Bucket Entry - detail::read( - is, result.offset); // Offset - detail::read( - is, result.size); // Size - detail::read( - is, result.hash); // Hash - return result; -} - -template -std::size_t -bucket_t<_>::lower_bound ( - std::size_t h) const -{ - // Bucket Entry - auto const w = - field::size + // Offset - field::size + // Size - field::size; // Hash - // Bucket Record - auto const p = p_ + - field::size + // Count - field::size + // Spill - // Bucket Entry - field::size + // Offset - field::size; // Size - std::size_t step; - std::size_t first = 0; - std::size_t count = size_; - while (count > 0) - { - step = count / 2; - auto const i = first + step; - std::size_t h1; - readp(p + i * w, h1); - if (h1 < h) - { - first = i + 1; - count -= step + 1; - } - else - { - count = step; - } - } - return first; -} - -template -void -bucket_t<_>::insert (std::size_t offset, - std::size_t size, std::size_t h) -{ - std::size_t i = lower_bound(h); - // Bucket Record - auto const p = p_ + - field< - std::uint16_t>::size + // Count - field::size; // Spill - // Bucket Entry - std::size_t const w = - field::size + // Offset - field::size + // Size - field::size; // Hash - std::memmove ( - p + (i + 1) * w, - p + i * w, - (size_ - i) * w); - size_++; - update(); - // Bucket Entry - ostream os (p + i * w, w); - detail::write( - os, offset); // Offset - detail::write( - os, size); // Size - detail::write( - os, h); // Prefix -} - -template -void -bucket_t<_>::erase (std::size_t i) -{ - // Bucket Record - auto const p = p_ + - field< - std::uint16_t>::size + // Count - field::size; // Spill - auto const w = - field::size + // Offset - field::size + // Size - field::size; // Hash - --size_; - if (i < size_) - std::memmove( - p + i * w, - p + (i + 1) * w, - (size_ - i) * w); - std::memset(p + size_ * w, 0, w); - update(); -} - -template -template -void -bucket_t<_>::read (File& f, std::size_t offset) -{ - auto const cap = bucket_capacity ( - block_size_); - // Excludes padding to block size - f.read (offset, p_, bucket_size(cap)); - istream is(p_, block_size_); - detail::read< - std::uint16_t>(is, size_); // Count - detail::read< - uint48_t>(is, spill_); // Spill - if (size_ > cap) - throw store_corrupt_error( - "bad bucket size"); -} - -template -template -void -bucket_t<_>::read (bulk_reader& r) -{ - // Bucket Record (compact) - auto is = r.prepare( - detail::field::size + - detail::field::size); - detail::read< - std::uint16_t>(is, size_); // Count - detail::read( - is, spill_); // Spill - update(); - // Excludes empty bucket entries - auto const w = size_ * ( - field::size + // Offset - field::size + // Size - field::size); // Hash - is = r.prepare (w); - std::memcpy(p_ + - field< - std::uint16_t>::size + // Count - field::size, // Spill - is.data(w), w); // Entries -} - -template -void -bucket_t<_>::write (ostream& os) const -{ - // Does not pad up to the block size. This - // is called to write to the data file. - auto const size = compact_size(); - // Bucket Record - std::memcpy (os.data(size), p_, size); -} - -template -template -void -bucket_t<_>::write (File& f, std::size_t offset) const -{ - // Includes zero pad up to the block - // size, to make the key file size always - // a multiple of the block size. - auto const size = compact_size(); - std::memset (p_ + size, 0, - block_size_ - size); - // Bucket Record - f.write (offset, p_, block_size_); -} - -template -void -bucket_t<_>::update() -{ - // Bucket Record - ostream os(p_, block_size_); - detail::write< - std::uint16_t>(os, size_); // Count - detail::write< - uint48_t>(os, spill_); // Spill -} - -using bucket = bucket_t<>; - -// Spill bucket if full. -// The bucket is cleared after it spills. -// -template -void -maybe_spill(bucket& b, bulk_writer& w) -{ - if (b.full()) - { - // Spill Record - auto const offset = w.offset(); - auto os = w.prepare( - field::size + // Zero - field::size + // Size - b.compact_size()); - write (os, 0); // Zero - write ( - os, b.compact_size()); // Size - auto const spill = - offset + os.size(); - b.write (os); // Bucket - // Update bucket - b.clear(); - b.spill (spill); - } -} - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/buffer.h b/beast/nudb/detail/buffer.h deleted file mode 100644 index 2c71912ece..0000000000 --- a/beast/nudb/detail/buffer.h +++ /dev/null @@ -1,99 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_BUFFER_H_INCLUDED -#define BEAST_NUDB_DETAIL_BUFFER_H_INCLUDED - -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// Simple growable memory buffer -class buffer -{ -private: - std::size_t size_ = 0; - std::unique_ptr buf_; - -public: - ~buffer() = default; - buffer() = default; - buffer (buffer const&) = delete; - buffer& operator= (buffer const&) = delete; - - explicit - buffer (std::size_t n) - : size_ (n) - , buf_ (new std::uint8_t[n]) - { - } - - buffer (buffer&& other) - : size_ (other.size_) - , buf_ (std::move(other.buf_)) - { - other.size_ = 0; - } - - buffer& operator= (buffer&& other) - { - size_ = other.size_; - buf_ = std::move(other.buf_); - other.size_ = 0; - return *this; - } - - std::size_t - size() const - { - return size_; - } - - std::uint8_t* - get() const - { - return buf_.get(); - } - - void - reserve (std::size_t n) - { - if (size_ < n) - buf_.reset (new std::uint8_t[n]); - size_ = n; - } - - // BufferFactory - void* - operator() (std::size_t n) - { - reserve(n); - return buf_.get(); - } -}; - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/bulkio.h b/beast/nudb/detail/bulkio.h deleted file mode 100644 index f2c252fdc2..0000000000 --- a/beast/nudb/detail/bulkio.h +++ /dev/null @@ -1,195 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_BULKIO_H_INCLUDED -#define BEAST_NUDB_DETAIL_BULKIO_H_INCLUDED - -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// Scans a file in sequential large reads -template -class bulk_reader -{ -private: - File& f_; - buffer buf_; - std::size_t last_; // size of file - std::size_t offset_; // current position - std::size_t avail_; // bytes left to read in buf - std::size_t used_; // bytes consumed in buf - -public: - bulk_reader (File& f, std::size_t offset, - std::size_t last, std::size_t buffer_size); - - std::size_t - offset() const - { - return offset_ - avail_; - } - - bool - eof() const - { - return offset() >= last_; - } - - istream - prepare (std::size_t needed); -}; - -template -bulk_reader::bulk_reader (File& f, std::size_t offset, - std::size_t last, std::size_t buffer_size) - : f_ (f) - , last_ (last) - , offset_ (offset) - , avail_ (0) - , used_ (0) -{ - buf_.reserve (buffer_size); -} - - -template -istream -bulk_reader::prepare (std::size_t needed) -{ - if (needed > avail_) - { - if (offset_ + needed - avail_ > last_) - throw file_short_read_error(); - if (needed > buf_.size()) - { - buffer buf; - buf.reserve (needed); - std::memcpy (buf.get(), - buf_.get() + used_, avail_); - buf_ = std::move(buf); - } - else - { - std::memmove (buf_.get(), - buf_.get() + used_, avail_); - } - - auto const n = std::min( - buf_.size() - avail_, last_ - offset_); - f_.read(offset_, buf_.get() + avail_, n); - offset_ += n; - avail_ += n; - used_ = 0; - } - istream is(buf_.get() + used_, needed); - used_ += needed; - avail_ -= needed; - return is; -} - -//------------------------------------------------------------------------------ - -// Buffers file writes -// Caller must call flush manually at the end -template -class bulk_writer -{ -private: - File& f_; - buffer buf_; - std::size_t offset_; // current position - std::size_t used_; // bytes written to buf - -public: - bulk_writer (File& f, std::size_t offset, - std::size_t buffer_size); - - ostream - prepare (std::size_t needed); - - // Returns the number of bytes buffered - std::size_t - size() - { - return used_; - } - - // Return current offset in file. This - // is advanced with each call to prepare. - std::size_t - offset() const - { - return offset_ + used_; - } - - // flush cannot be called from the destructor - // since it can throw, so callers must do it manually. - void - flush(); -}; - -template -bulk_writer::bulk_writer (File& f, - std::size_t offset, std::size_t buffer_size) - : f_ (f) - , offset_ (offset) - , used_ (0) - -{ - buf_.reserve (buffer_size); -} - -template -ostream -bulk_writer::prepare (std::size_t needed) -{ - if (used_ + needed > buf_.size()) - flush(); - if (needed > buf_.size()) - buf_.reserve (needed); - ostream os (buf_.get() + used_, needed); - used_ += needed; - return os; -} - -template -void -bulk_writer::flush() -{ - if (used_) - { - auto const offset = offset_; - auto const used = used_; - offset_ += used_; - used_ = 0; - f_.write (offset, buf_.get(), used); - } -} - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/cache.h b/beast/nudb/detail/cache.h deleted file mode 100644 index 5c97ffad81..0000000000 --- a/beast/nudb/detail/cache.h +++ /dev/null @@ -1,247 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_CACHE_H_INCLUDED -#define BEAST_NUDB_DETAIL_CACHE_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// Associative container storing -// bucket blobs keyed by bucket index. -template -class cache_t -{ -public: - using value_type = std::pair< - std::size_t, bucket>; - -private: - enum - { - // The arena's alloc size will be this - // multiple of the block size. - factor = 64 - }; - - using map_type = std::unordered_map < - std::size_t, void*>; - - struct transform - { - using argument_type = - typename map_type::value_type; - using result_type = value_type; - - cache_t* cache_; - - transform() - : cache_ (nullptr) - { - } - - explicit - transform (cache_t& cache) - : cache_ (&cache) - { - } - - value_type - operator() (argument_type const& e) const - { - return std::make_pair(e.first, - bucket (cache_->block_size_, - e.second)); - } - }; - - std::size_t key_size_; - std::size_t block_size_; - arena arena_; - map_type map_; - -public: - using iterator = boost::transform_iterator< - transform, typename map_type::iterator, - value_type, value_type>; - - cache_t (cache_t const&) = delete; - cache_t& operator= (cache_t const&) = delete; - - cache_t(); - - explicit - cache_t (std::size_t key_size, - std::size_t block_size); - - cache_t& operator= (cache_t&& other); - - iterator - begin() - { - return iterator(map_.begin(), - transform(*this)); - } - - iterator - end() - { - return iterator(map_.end(), - transform(*this)); - } - - bool - empty() const - { - return map_.empty(); - } - - void - clear(); - - void - shrink_to_fit(); - - iterator - find (std::size_t n); - - // Create an empty bucket - // - bucket - create (std::size_t n); - - // Insert a copy of a bucket. - // - iterator - insert (std::size_t n, bucket const& b); - - template - friend - void - swap (cache_t& lhs, cache_t& rhs); -}; - -// Constructs a cache that will never have inserts -template -cache_t<_>::cache_t() - : key_size_ (0) - , block_size_ (0) - , arena_ (32) // arbitrary small number -{ -} - -template -cache_t<_>::cache_t (std::size_t key_size, - std::size_t block_size) - : key_size_ (key_size) - , block_size_ (block_size) - , arena_ (block_size * factor) -{ -} - -template -cache_t<_>& -cache_t<_>::operator=(cache_t&& other) -{ - arena_ = std::move(other.arena_); - map_ = std::move(other.map_); - return *this; -} - -template -void -cache_t<_>::clear() -{ - arena_.clear(); - map_.clear(); -} - -template -void -cache_t<_>::shrink_to_fit() -{ - arena_.shrink_to_fit(); -} - -template -auto -cache_t<_>::find (std::size_t n) -> - iterator -{ - auto const iter = map_.find(n); - if (iter == map_.end()) - return iterator (map_.end(), - transform(*this)); - return iterator (iter, - transform(*this)); -} - -template -bucket -cache_t<_>::create (std::size_t n) -{ - auto const p = arena_.alloc (block_size_); - map_.emplace (n, p); - return bucket (block_size_, - p, detail::empty); -} - -template -auto -cache_t<_>::insert (std::size_t n, - bucket const& b) -> - iterator -{ - void* const p = arena_.alloc( - b.block_size()); - ostream os(p, b.block_size()); - b.write(os); - auto const result = map_.emplace(n, p); - return iterator(result.first, - transform(*this)); -} - -template -void -swap (cache_t& lhs, cache_t& rhs) -{ - using std::swap; - swap(lhs.key_size_, rhs.key_size_); - swap(lhs.block_size_, rhs.block_size_); - swap(lhs.arena_, rhs.arena_); - swap(lhs.map_, rhs.map_); -} - -using cache = cache_t<>; - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/field.h b/beast/nudb/detail/field.h deleted file mode 100644 index b82ab78b35..0000000000 --- a/beast/nudb/detail/field.h +++ /dev/null @@ -1,275 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_FIELD_H_INCLUDED -#define BEAST_NUDB_FIELD_H_INCLUDED - -#include -#include // for BEAST_CONSTEXPR -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// A 24-bit integer -struct uint24_t; - -// A 48-bit integer -struct uint48_t; - -// These metafunctions describe the binary format of fields on disk - -template -struct field; - -template <> -struct field -{ - static std::size_t BEAST_CONSTEXPR size = 1; - static std::size_t BEAST_CONSTEXPR max = 0xff; -}; - -template <> -struct field -{ - static std::size_t BEAST_CONSTEXPR size = 2; - static std::size_t BEAST_CONSTEXPR max = 0xffff; -}; - -template <> -struct field -{ - static std::size_t BEAST_CONSTEXPR size = 3; - static std::size_t BEAST_CONSTEXPR max = 0xffffff; -}; - -template <> -struct field -{ - static std::size_t BEAST_CONSTEXPR size = 4; - static std::size_t BEAST_CONSTEXPR max = 0xffffffff; -}; - -template <> -struct field -{ - static std::size_t BEAST_CONSTEXPR size = 6; - static std::size_t BEAST_CONSTEXPR max = 0x0000ffffffffffff; -}; - -template <> -struct field -{ - static std::size_t BEAST_CONSTEXPR size = 8; - static std::size_t BEAST_CONSTEXPR max = 0xffffffffffffffff; -}; - -// read field from memory - -template ::value>* = nullptr> -void -readp (void const* v, U& u) -{ - std::uint8_t const* p = - reinterpret_cast(v); - u = *p; -} - -template ::value>* = nullptr> -void -readp (void const* v, U& u) -{ - std::uint8_t const* p = - reinterpret_cast(v); - T t; - t = T(*p++)<< 8; - t = T(*p ) | t; - u = t; -} - -template ::value>* = nullptr> -void -readp (void const* v, U& u) -{ - std::uint8_t const* p = - reinterpret_cast(v); - std::uint32_t t; - t = std::uint32_t(*p++)<<16; - t = (std::uint32_t(*p++)<< 8) | t; - t = std::uint32_t(*p ) | t; - u = t; -} - -template ::value>* = nullptr> -void -readp (void const* v, U& u) -{ - std::uint8_t const* p = - reinterpret_cast(v); - T t; - t = T(*p++)<<24; - t = (T(*p++)<<16) | t; - t = (T(*p++)<< 8) | t; - t = T(*p ) | t; - u = t; -} - -template ::value>* = nullptr> -void -readp (void const* v, U& u) -{ - std::uint8_t const* p = - reinterpret_cast(v); - std::uint64_t t; - t = (std::uint64_t(*p++)<<40); - t = (std::uint64_t(*p++)<<32) | t; - t = (std::uint64_t(*p++)<<24) | t; - t = (std::uint64_t(*p++)<<16) | t; - t = (std::uint64_t(*p++)<< 8) | t; - t = std::uint64_t(*p ) | t; - u = t; -} - -template ::value>* = nullptr> -void -readp (void const* v, U& u) -{ - std::uint8_t const* p = - reinterpret_cast(v); - T t; - t = T(*p++)<<56; - t = (T(*p++)<<48) | t; - t = (T(*p++)<<40) | t; - t = (T(*p++)<<32) | t; - t = (T(*p++)<<24) | t; - t = (T(*p++)<<16) | t; - t = (T(*p++)<< 8) | t; - t = T(*p ) | t; - u = t; -} - -// read field from istream - -template -void -read (istream& is, U& u) -{ - readp(is.data(field::size), u); -} - -// write field to ostream - -template ::value>* = nullptr> -void -write (ostream& os, U const& u) -{ - std::uint8_t* p = - os.data(field::size); - *p = u; -} - -template ::value>* = nullptr> -void -write (ostream& os, U const& u) -{ - T t = u; - std::uint8_t* p = - os.data(field::size); - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -template ::value>* = nullptr> -void -write (ostream& os, U const& u) -{ - T t = u; - std::uint8_t* p = - os.data(field::size); - *p++ = (t>>16)&0xff; - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -template ::value>* = nullptr> -void -write (ostream& os, U const& u) -{ - T t = u; - std::uint8_t* p = - os.data(field::size); - *p++ = (t>>24)&0xff; - *p++ = (t>>16)&0xff; - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -template ::value>* = nullptr> -void -write (ostream& os, U const& u) -{ - std::uint64_t const t = u; - std::uint8_t* p = - os.data(field::size); - *p++ = (t>>40)&0xff; - *p++ = (t>>32)&0xff; - *p++ = (t>>24)&0xff; - *p++ = (t>>16)&0xff; - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -template ::value>* = nullptr> -void -write (ostream& os, U const& u) -{ - T t = u; - std::uint8_t* p = - os.data(field::size); - *p++ = (t>>56)&0xff; - *p++ = (t>>48)&0xff; - *p++ = (t>>40)&0xff; - *p++ = (t>>32)&0xff; - *p++ = (t>>24)&0xff; - *p++ = (t>>16)&0xff; - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/format.h b/beast/nudb/detail/format.h deleted file mode 100644 index 318fc6fa17..0000000000 --- a/beast/nudb/detail/format.h +++ /dev/null @@ -1,582 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_FORMAT_H_INCLUDED -#define BEAST_NUDB_DETAIL_FORMAT_H_INCLUDED - -#include -#include -#include -#include -#include // for BEAST_CONSTEXPR -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// Format of the nudb files: - -static std::size_t BEAST_CONSTEXPR currentVersion = 2; - -struct dat_file_header -{ - static std::size_t BEAST_CONSTEXPR size = - 8 + // Type - 2 + // Version - 8 + // UID - 8 + // Appnum - 2 + // KeySize - - 64; // (Reserved) - - char type[8]; - std::size_t version; - std::uint64_t uid; - std::uint64_t appnum; - std::size_t key_size; -}; - -struct key_file_header -{ - static std::size_t BEAST_CONSTEXPR size = - 8 + // Type - 2 + // Version - 8 + // UID - 8 + // Appnum - 2 + // KeySize - - 8 + // Salt - 8 + // Pepper - 2 + // BlockSize - 2 + // LoadFactor - - 56; // (Reserved) - - char type[8]; - std::size_t version; - std::uint64_t uid; - std::uint64_t appnum; - std::size_t key_size; - - std::uint64_t salt; - std::uint64_t pepper; - std::size_t block_size; - std::size_t load_factor; - - // Computed values - std::size_t capacity; - std::size_t bucket_size; - std::size_t buckets; - std::size_t modulus; -}; - -struct log_file_header -{ - static std::size_t BEAST_CONSTEXPR size = - 8 + // Type - 2 + // Version - 8 + // UID - 8 + // Appnum - 2 + // KeySize - - 8 + // Salt - 8 + // Pepper - 2 + // BlockSize - - 8 + // KeyFileSize - 8; // DataFileSize - - char type[8]; - std::size_t version; - std::uint64_t uid; - std::uint64_t appnum; - std::size_t key_size; - std::uint64_t salt; - std::uint64_t pepper; - std::size_t block_size; - std::size_t key_file_size; - std::size_t dat_file_size; -}; - -// Type used to store hashes in buckets. -// This can be smaller than the output -// of the hash function. -// -using hash_t = uint48_t; - -static_assert(field::size <= - sizeof(std::size_t), ""); - -template -std::size_t -make_hash (std::size_t h); - -template<> -inline -std::size_t -make_hash(std::size_t h) -{ - return (h>>16)&0xffffffffffff; -} - -// Returns the hash of a key given the salt. -// Note: The hash is expressed in hash_t units -// -template -inline -std::size_t -hash (void const* key, - std::size_t key_size, std::size_t salt) -{ - Hasher h (salt); - h (key, key_size); - return make_hash(static_cast< - typename Hasher::result_type>(h)); -} - -// Computes pepper from salt -// -template -std::size_t -pepper (std::size_t salt) -{ - Hasher h (salt); - h (&salt, sizeof(salt)); - return static_cast(h); -} - -// Returns the actual size of a bucket. -// This can be smaller than the block size. -// -template -std::size_t -bucket_size (std::size_t capacity) -{ - // Bucket Record - return - field::size + // Count - field::size + // Spill - capacity * ( - field::size + // Offset - field::size + // Size - field::size); // Hash -} - -// Returns the number of entries that fit in a bucket -// -template -std::size_t -bucket_capacity (std::size_t block_size) -{ - // Bucket Record - auto const size = - field::size + // Count - field::size; // Spill - auto const entry_size = - field::size + // Offset - field::size + // Size - field::size; // Hash - if (block_size < key_file_header::size || - block_size < size) - return 0; - return (block_size - size) / entry_size; -} - -// Returns the number of bytes occupied by a value record -inline -std::size_t -value_size (std::size_t size, - std::size_t key_size) -{ - // Data Record - return - field::size + // Size - key_size + // Key - size; // Data -} - -// Returns the closest power of 2 not less than x -template -std::size_t -ceil_pow2 (unsigned long long x) -{ - static const unsigned long long t[6] = { - 0xFFFFFFFF00000000ull, - 0x00000000FFFF0000ull, - 0x000000000000FF00ull, - 0x00000000000000F0ull, - 0x000000000000000Cull, - 0x0000000000000002ull - }; - - int y = (((x & (x - 1)) == 0) ? 0 : 1); - int j = 32; - int i; - - for(i = 0; i < 6; i++) { - int k = (((x & t[i]) == 0) ? 0 : j); - y += k; - x >>= k; - j >>= 1; - } - - return std::size_t(1)< -void -read (istream& is, dat_file_header& dh) -{ - read (is, dh.type, sizeof(dh.type)); - read(is, dh.version); - read(is, dh.uid); - read(is, dh.appnum); - read(is, dh.key_size); - std::array reserved; - read (is, - reserved.data(), reserved.size()); -} - -// Read data file header from file -template -void -read (File& f, dat_file_header& dh) -{ - std::array buf; - try - { - f.read(0, buf.data(), buf.size()); - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "short data file header"); - } - istream is(buf); - read (is, dh); -} - -// Write data file header to stream -template -void -write (ostream& os, dat_file_header const& dh) -{ - write (os, "nudb.dat", 8); - write(os, dh.version); - write(os, dh.uid); - write(os, dh.appnum); - write(os, dh.key_size); - std::array reserved; - reserved.fill(0); - write (os, - reserved.data(), reserved.size()); -} - -// Write data file header to file -template -void -write (File& f, dat_file_header const& dh) -{ - std::array buf; - ostream os(buf); - write(os, dh); - f.write (0, buf.data(), buf.size()); -} - -// Read key file header from stream -template -void -read (istream& is, std::size_t file_size, - key_file_header& kh) -{ - read(is, kh.type, sizeof(kh.type)); - read(is, kh.version); - read(is, kh.uid); - read(is, kh.appnum); - read(is, kh.key_size); - read(is, kh.salt); - read(is, kh.pepper); - read(is, kh.block_size); - read(is, kh.load_factor); - std::array reserved; - read (is, - reserved.data(), reserved.size()); - - // VFALCO These need to be checked to handle - // when the file size is too small - kh.capacity = bucket_capacity(kh.block_size); - kh.bucket_size = bucket_size(kh.capacity); - if (file_size > kh.block_size) - { - // VFALCO This should be handled elsewhere. - // we shouldn't put the computed fields - // in this header. - if (kh.block_size > 0) - kh.buckets = (file_size - kh.bucket_size) - / kh.block_size; - else - // VFALCO Corruption or logic error - kh.buckets = 0; - } - else - { - kh.buckets = 0; - } - kh.modulus = ceil_pow2(kh.buckets); -} - -// Read key file header from file -template -void -read (File& f, key_file_header& kh) -{ - std::array buf; - try - { - f.read(0, buf.data(), buf.size()); - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "short key file header"); - } - istream is(buf); - read (is, f.actual_size(), kh); -} - -// Write key file header to stream -template -void -write (ostream& os, key_file_header const& kh) -{ - write (os, "nudb.key", 8); - write(os, kh.version); - write(os, kh.uid); - write(os, kh.appnum); - write(os, kh.key_size); - write(os, kh.salt); - write(os, kh.pepper); - write(os, kh.block_size); - write(os, kh.load_factor); - std::array reserved; - reserved.fill (0); - write (os, - reserved.data(), reserved.size()); -} - -// Write key file header to file -template -void -write (File& f, key_file_header const& kh) -{ - buffer buf; - buf.reserve (kh.block_size); - if (kh.block_size < key_file_header::size) - throw std::logic_error( - "nudb: block size too small"); - std::fill(buf.get(), buf.get() + buf.size(), 0); - ostream os (buf.get(), buf.size()); - write (os, kh); - f.write (0, buf.get(), buf.size()); -} - -// Read log file header from stream -template -void -read (istream& is, log_file_header& lh) -{ - read (is, lh.type, sizeof(lh.type)); - read(is, lh.version); - read(is, lh.uid); - read(is, lh.appnum); - read(is, lh.key_size); - read(is, lh.salt); - read(is, lh.pepper); - read(is, lh.block_size); - read(is, lh.key_file_size); - read(is, lh.dat_file_size); -} - -// Read log file header from file -template -void -read (File& f, log_file_header& lh) -{ - std::array buf; - // Can throw file_short_read_error to callers - f.read (0, buf.data(), buf.size()); - istream is(buf); - read (is, lh); -} - -// Write log file header to stream -template -void -write (ostream& os, log_file_header const& lh) -{ - write (os, "nudb.log", 8); - write(os, lh.version); - write(os, lh.uid); - write(os, lh.appnum); - write(os, lh.key_size); - write(os, lh.salt); - write(os, lh.pepper); - write(os, lh.block_size); - write(os, lh.key_file_size); - write(os, lh.dat_file_size); -} - -// Write log file header to file -template -void -write (File& f, log_file_header const& lh) -{ - std::array buf; - ostream os (buf); - write (os, lh); - f.write (0, buf.data(), buf.size()); -} - -template -void -verify (dat_file_header const& dh) -{ - std::string const type (dh.type, 8); - if (type != "nudb.dat") - throw store_corrupt_error ( - "bad type in data file"); - if (dh.version != currentVersion) - throw store_corrupt_error ( - "bad version in data file"); - if (dh.key_size < 1) - throw store_corrupt_error ( - "bad key size in data file"); -} - -template -void -verify (key_file_header const& kh) -{ - std::string const type (kh.type, 8); - if (type != "nudb.key") - throw store_corrupt_error ( - "bad type in key file"); - if (kh.version != currentVersion) - throw store_corrupt_error ( - "bad version in key file"); - if (kh.key_size < 1) - throw store_corrupt_error ( - "bad key size in key file"); - if (kh.pepper != pepper(kh.salt)) - throw store_corrupt_error( - "wrong hash function for key file"); - if (kh.load_factor < 1) - throw store_corrupt_error ( - "bad load factor in key file"); - if (kh.capacity < 1) - throw store_corrupt_error ( - "bad capacity in key file"); - if (kh.buckets < 1) - throw store_corrupt_error ( - "bad key file size"); -} - -template -void -verify (log_file_header const& lh) -{ - std::string const type (lh.type, 8); - if (type != "nudb.log") - throw store_corrupt_error ( - "bad type in log file"); - if (lh.version != currentVersion) - throw store_corrupt_error ( - "bad version in log file"); - if (lh.pepper != pepper(lh.salt)) - throw store_corrupt_error( - "wrong hash function for log file"); - if (lh.key_size < 1) - throw store_corrupt_error ( - "bad key size in log file"); -} - -// Make sure key file and value file headers match -template -void -verify (dat_file_header const& dh, - key_file_header const& kh) -{ - verify (kh); - if (kh.uid != dh.uid) - throw store_corrupt_error( - "uid mismatch"); - if (kh.appnum != dh.appnum) - throw store_corrupt_error( - "appnum mismatch"); - if (kh.key_size != dh.key_size) - throw store_corrupt_error( - "key size mismatch"); -} - -template -void -verify (key_file_header const& kh, - log_file_header const& lh) -{ - verify(lh); - if (kh.uid != lh.uid) - throw store_corrupt_error ( - "uid mismatch in log file"); - if (kh.appnum != lh.appnum) - throw store_corrupt_error( - "appnum mismatch in log file"); - if (kh.key_size != lh.key_size) - throw store_corrupt_error ( - "key size mismatch in log file"); - if (kh.salt != lh.salt) - throw store_corrupt_error ( - "salt mismatch in log file"); - if (kh.pepper != lh.pepper) - throw store_corrupt_error ( - "pepper mismatch in log file"); - if (kh.block_size != lh.block_size) - throw store_corrupt_error ( - "block size mismatch in log file"); -} - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/gentex.h b/beast/nudb/detail/gentex.h deleted file mode 100644 index c0f960cf8a..0000000000 --- a/beast/nudb/detail/gentex.h +++ /dev/null @@ -1,274 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_GENTEX_H_INCLUDED -#define BEAST_NUDB_DETAIL_GENTEX_H_INCLUDED - -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// Generation counting mutex -// -template -class gentex_t -{ -private: - std::mutex m_; - std::size_t gen_ = 0; - std::size_t cur_ = 0; - std::size_t prev_ = 0; - std::condition_variable cond_; - -public: - gentex_t() = default; - gentex_t (gentex_t const&) = delete; - gentex_t& operator= (gentex_t const&) = delete; - - void - start(); - - void - finish(); - - std::size_t - lock_gen(); - - void - unlock_gen (std::size_t gen); -}; - -template -void -gentex_t<_>::start() -{ - std::lock_guard< - std::mutex> l(m_); - prev_ += cur_; - cur_ = 0; - ++gen_; -} - -template -void -gentex_t<_>::finish() -{ - std::unique_lock< - std::mutex> l(m_); - while (prev_ > 0) - cond_.wait(l); -} - -template -std::size_t -gentex_t<_>::lock_gen() -{ - std::lock_guard< - std::mutex> l(m_); - ++cur_; - return gen_; -} - -template -void -gentex_t<_>::unlock_gen ( - std::size_t gen) -{ - std::lock_guard< - std::mutex> l(m_); - if (gen == gen_) - { - --cur_; - } - else - { - --prev_; - if (prev_ == 0) - cond_.notify_all(); - } -} - -using gentex = gentex_t<>; - -//------------------------------------------------------------------------------ - -template -class genlock -{ -private: - bool owned_ = false; - GenerationLockable* g_ = nullptr; - std::size_t gen_; - -public: - using mutex_type = GenerationLockable; - - genlock() = default; - genlock (genlock const&) = delete; - genlock& operator= (genlock const&) = delete; - - genlock (genlock&& other); - - genlock& operator= (genlock&& other); - - explicit - genlock (mutex_type& g); - - genlock (mutex_type& g, std::defer_lock_t); - - ~genlock(); - - mutex_type* - mutex() noexcept - { - return g_; - } - - bool - owns_lock() const noexcept - { - return g_ && owned_; - } - - explicit - operator bool() const noexcept - { - return owns_lock(); - } - - void - lock(); - - void - unlock(); - - mutex_type* - release() noexcept; - - template - friend - void - swap (genlock& lhs, genlock& rhs) noexcept; -}; - -template -genlock::genlock (genlock&& other) - : owned_ (other.owned_) - , g_ (other.g_) -{ - other.owned_ = false; - other.g_ = nullptr; -} - -template -genlock& -genlock::operator= (genlock&& other) -{ - if (owns_lock()) - unlock(); - owned_ = other.owned_; - g_ = other.g_; - other.owned_ = false; - other.g_ = nullptr; - return *this; -} - -template -genlock::genlock (mutex_type& g) - : g_ (&g) -{ - lock(); -} - -template -genlock::genlock ( - mutex_type& g, std::defer_lock_t) - : g_ (&g) -{ -} - -template -genlock::~genlock() -{ - if (owns_lock()) - unlock(); -} - -template -void -genlock::lock() -{ - if (! g_) - throw std::system_error(std::make_error_code( - std::errc::operation_not_permitted), - "genlock: no associated mutex"); - if (owned_) - throw std::system_error(std::make_error_code( - std::errc::resource_deadlock_would_occur), - "genlock: already owned"); - gen_ = g_->lock_gen(); - owned_ = true; -} - -template -void -genlock::unlock() -{ - if (! g_) - throw std::system_error(std::make_error_code( - std::errc::operation_not_permitted), - "genlock: no associated mutex"); - if (! owned_) - throw std::system_error(std::make_error_code( - std::errc::operation_not_permitted), - "genlock: not owned"); - g_->unlock_gen (gen_); - owned_ = false; -} - -template -auto -genlock::release() noexcept -> - mutex_type* -{ - mutex_type* const g = g_; - g_ = nullptr; - return g; -} - -template -void -swap (genlock& lhs, genlock& rhs) noexcept -{ - using namespace std; - swap (lhs.owned_, rhs.owned_); - swap (lhs.g_, rhs.g_); -} - -} // detail -} // nudb -} // beast - - -#endif diff --git a/beast/nudb/detail/pool.h b/beast/nudb/detail/pool.h deleted file mode 100644 index c3397c1591..0000000000 --- a/beast/nudb/detail/pool.h +++ /dev/null @@ -1,255 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_POOL_H_INCLUDED -#define BEAST_NUDB_DETAIL_POOL_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// Buffers key/value pairs in a map, associating -// them with a modifiable data file offset. -template -class pool_t -{ -public: - struct value_type; - class compare; - -private: - using map_type = std::map< - value_type, std::size_t, compare>; - - arena arena_; - std::size_t key_size_; - std::size_t data_size_ = 0; - map_type map_; - -public: - using iterator = - typename map_type::iterator; - - pool_t (pool_t const&) = delete; - pool_t& operator= (pool_t const&) = delete; - - explicit - pool_t (std::size_t key_size, - std::size_t alloc_size); - - pool_t& operator= (pool_t&& other); - - iterator - begin() - { - return map_.begin(); - } - - iterator - end() - { - return map_.end(); - } - - bool - empty() - { - return map_.size() == 0; - } - - // Returns the number of elements in the pool - std::size_t - size() const - { - return map_.size(); - } - - // Returns the sum of data sizes in the pool - std::size_t - data_size() const - { - return data_size_; - } - - void - clear(); - - void - shrink_to_fit(); - - iterator - find (void const* key); - - // Insert a value - // @param h The hash of the key - void - insert (std::size_t h, void const* key, - void const* buffer, std::size_t size); - - template - friend - void - swap (pool_t& lhs, pool_t& rhs); -}; - -template -struct pool_t<_>::value_type -{ - std::size_t hash; - std::size_t size; - void const* key; - void const* data; - - value_type (value_type const&) = default; - value_type& operator= (value_type const&) = default; - - value_type (std::size_t hash_, std::size_t size_, - void const* key_, void const* data_) - : hash (hash_) - , size (size_) - , key (key_) - , data (data_) - { - } -}; - -template -class pool_t<_>::compare -{ -private: - std::size_t key_size_; - -public: - using result_type = bool; - using first_argument_type = value_type; - using second_argument_type = value_type; - - compare (compare const&) = default; - compare& operator= (compare const&) = default; - - compare (std::size_t key_size) - : key_size_ (key_size) - { - } - - bool - operator()(value_type const& lhs, - value_type const& rhs) const - { - return std::memcmp( - lhs.key, rhs.key, key_size_) < 0; - } -}; - -//------------------------------------------------------------------------------ - -template -pool_t<_>::pool_t (std::size_t key_size, - std::size_t alloc_size) - : arena_ (alloc_size) - , key_size_ (key_size) - , map_ (compare(key_size)) -{ -} - -template -pool_t<_>& -pool_t<_>::operator= (pool_t&& other) -{ - arena_ = std::move(other.arena_); - key_size_ = other.key_size_; - data_size_ = other.data_size_; - map_ = std::move(other.map_); - return *this; -} - -template -void -pool_t<_>::clear() -{ - arena_.clear(); - data_size_ = 0; - map_.clear(); -} - -template -void -pool_t<_>::shrink_to_fit() -{ - arena_.shrink_to_fit(); -} - -template -auto -pool_t<_>::find (void const* key) -> - iterator -{ - // VFALCO need is_transparent here - value_type tmp (0, 0, key, nullptr); - auto const iter = map_.find(tmp); - return iter; -} - -template -void -pool_t<_>::insert (std::size_t h, - void const* key, void const* data, - std::size_t size) -{ - auto const k = arena_.alloc(key_size_); - auto const d = arena_.alloc(size); - std::memcpy(k, key, key_size_); - std::memcpy(d, data, size); - auto const result = map_.emplace( - std::piecewise_construct, - std::make_tuple(h, size, k, d), - std::make_tuple(0)); - (void)result.second; - // Must not already exist! - assert(result.second); - data_size_ += size; -} - -template -void -swap (pool_t<_>& lhs, pool_t<_>& rhs) -{ - using std::swap; - swap(lhs.arena_, rhs.arena_); - swap(lhs.key_size_, rhs.key_size_); - swap(lhs.data_size_, rhs.data_size_); - swap(lhs.map_, rhs.map_); -} - -using pool = pool_t<>; - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/stream.h b/beast/nudb/detail/stream.h deleted file mode 100644 index 901b5deecd..0000000000 --- a/beast/nudb/detail/stream.h +++ /dev/null @@ -1,162 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_STREAM_H_INCLUDED -#define BEAST_NUDB_DETAIL_STREAM_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// Input stream from bytes -template -class istream_t -{ -private: - std::uint8_t const* buf_; - std::size_t size_ = 0; - -public: - istream_t (istream_t const&) = default; - istream_t& operator= (istream_t const&) = default; - - istream_t (void const* data, std::size_t size) - : buf_(reinterpret_cast< - std::uint8_t const*>(data)) - , size_(size) - { - } - - template - istream_t (std::array const& a) - : buf_ (a.data()) - , size_ (a.size()) - { - } - - std::uint8_t const* - data (std::size_t bytes); - - std::uint8_t const* - operator()(std::size_t bytes) - { - return data(bytes); - } -}; - -template -std::uint8_t const* -istream_t<_>::data (std::size_t bytes) -{ - if (size_ < bytes) - throw short_read_error(); - auto const data = buf_; - buf_ = buf_ + bytes; - size_ -= bytes; - return data; -} - -using istream = istream_t<>; - -//------------------------------------------------------------------------------ - -// Output stream to bytes -template -class ostream_t -{ -private: - std::uint8_t* buf_; - std::size_t size_ = 0; - -public: - ostream_t (ostream_t const&) = default; - ostream_t& operator= (ostream_t const&) = default; - - ostream_t (void* data, std::size_t) - : buf_ (reinterpret_cast(data)) - { - } - - template - ostream_t (std::array& a) - : buf_ (a.data()) - { - } - - // Returns the number of bytes written - std::size_t - size() const - { - return size_; - } - - std::uint8_t* - data (std::size_t bytes); - - std::uint8_t* - operator()(std::size_t bytes) - { - return data(bytes); - } -}; - -template -std::uint8_t* -ostream_t<_>::data (std::size_t bytes) -{ - auto const data = buf_; - buf_ = buf_ + bytes; - size_ += bytes; - return data; -} - -using ostream = ostream_t<>; - -//------------------------------------------------------------------------------ - -// read blob -inline -void -read (istream& is, - void* buffer, std::size_t bytes) -{ - std::memcpy (buffer, is.data(bytes), bytes); -} - -// write blob -inline -void -write (ostream& os, - void const* buffer, std::size_t bytes) -{ - std::memcpy (os.data(bytes), buffer, bytes); -} - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/detail/varint.h b/beast/nudb/detail/varint.h deleted file mode 100644 index c194b909ca..0000000000 --- a/beast/nudb/detail/varint.h +++ /dev/null @@ -1,155 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_VARINT_H_INCLUDED -#define BEAST_NUDB_VARINT_H_INCLUDED - -#include // for BEAST_CONSTEXPR -#include -#include -#include - -namespace beast { -namespace nudb { -namespace detail { - -// base128 varint format is from -// google protocol buffers: -// https://developers.google.com/protocol-buffers/docs/encoding#varints - -// field tag -struct varint; - -// Metafuncton to return largest -// possible size of T represented as varint. -// T must be unsigned -template ::value> -struct varint_traits; - -template -struct varint_traits -{ - static std::size_t BEAST_CONSTEXPR max = - (8 * sizeof(T) + 6) / 7; -}; - -// Returns: Number of bytes consumed or 0 on error, -// if the buffer was too small or t overflowed. -// -template -std::size_t -read_varint (void const* buf, - std::size_t buflen, std::size_t& t) -{ - t = 0; - std::uint8_t const* p = - reinterpret_cast< - std::uint8_t const*>(buf); - std::size_t n = 0; - while (p[n] & 0x80) - if (++n >= buflen) - return 0; - if (++n > buflen) - return 0; - // Special case for 0 - if (n == 1 && *p == 0) - { - t = 0; - return 1; - } - auto const used = n; - while (n--) - { - auto const d = p[n]; - auto const t0 = t; - t *= 127; - t += d & 0x7f; - if (t <= t0) - return 0; // overflow - } - return used; -} - -template ::value>* = nullptr> -std::size_t -size_varint (T v) -{ - std::size_t n = 0; - do - { - v /= 127; - ++n; - } - while (v != 0); - return n; -} - -template -std::size_t -write_varint (void* p0, std::size_t v) -{ - std::uint8_t* p = reinterpret_cast< - std::uint8_t*>(p0); - do - { - std::uint8_t d = - v % 127; - v /= 127; - if (v != 0) - d |= 0x80; - *p++ = d; - } - while (v != 0); - return p - reinterpret_cast< - std::uint8_t*>(p0); -} - -// input stream - -template ::value>* = nullptr> -void -read (istream& is, std::size_t& u) -{ - auto p0 = is(1); - auto p1 = p0; - while (*p1++ & 0x80) - is(1); - read_varint(p0, p1 - p0, u); -} - -// output stream - -template ::value>* = nullptr> -void -write (ostream& os, std::size_t t) -{ - write_varint(os.data( - size_varint(t)), t); -} - -} // detail -} // nudb -} // beast - -#endif diff --git a/beast/nudb/file.h b/beast/nudb/file.h deleted file mode 100644 index f04f4ae1fd..0000000000 --- a/beast/nudb/file.h +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_FILE_H_INCLUDED -#define BEAST_NUDB_FILE_H_INCLUDED - -#include -#include -#include - -namespace beast { -namespace nudb { - -using native_file = -#ifdef _MSC_VER - win32_file; -#else - posix_file; -#endif - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/identity.h b/beast/nudb/identity.h deleted file mode 100644 index 18b3dcad8e..0000000000 --- a/beast/nudb/identity.h +++ /dev/null @@ -1,64 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_IDENTITY_CODEC_H_INCLUDED -#define BEAST_NUDB_IDENTITY_CODEC_H_INCLUDED - -#include - -namespace beast { -namespace nudb { - -/** Codec which maps input directly to output. */ -class identity -{ -public: - template - explicit - identity(Args&&... args) - { - } - - char const* - name() const - { - return "none"; - } - - template - std::pair - compress (void const* in, - std::size_t in_size, BufferFactory&&) const - { - return std::make_pair(in, in_size); - } - - template - std::pair - decompress (void const* in, - std::size_t in_size, BufferFactory&&) const - { - return std::make_pair(in, in_size); - } -}; - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/nudb.cpp b/beast/nudb/nudb.cpp deleted file mode 100644 index 1888a95440..0000000000 --- a/beast/nudb/nudb.cpp +++ /dev/null @@ -1,24 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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 -#include -#include -#include -#include diff --git a/beast/nudb/posix_file.h b/beast/nudb/posix_file.h deleted file mode 100644 index 033b4c7d3c..0000000000 --- a/beast/nudb/posix_file.h +++ /dev/null @@ -1,376 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_POSIX_FILE_H_INCLUDED -#define BEAST_NUDB_DETAIL_POSIX_FILE_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -#ifndef BEAST_NUDB_POSIX_FILE -# ifdef _MSC_VER -# define BEAST_NUDB_POSIX_FILE 0 -# else -# define BEAST_NUDB_POSIX_FILE 1 -# endif -#endif - -#if BEAST_NUDB_POSIX_FILE -# include -# include -# include -# include -# include -#endif - -namespace beast { -namespace nudb { - -#if BEAST_NUDB_POSIX_FILE - -namespace detail { - -class file_posix_error : public file_error -{ -public: - explicit - file_posix_error (char const* m, - int errnum = errno) - : file_error (std::string("nudb: ") + m + - ", " + text(errnum)) - { - } - - explicit - file_posix_error (std::string const& m, - int errnum = errno) - : file_error (std::string("nudb: ") + m + - ", " + text(errnum)) - { - } - -private: - static - std::string - text (int errnum) - { - return std::strerror(errnum); - } -}; - -//------------------------------------------------------------------------------ - -template -class posix_file -{ -private: - int fd_ = -1; - -public: - posix_file() = default; - posix_file (posix_file const&) = delete; - posix_file& operator= (posix_file const&) = delete; - - ~posix_file(); - - posix_file (posix_file&&); - - posix_file& - operator= (posix_file&& other); - - bool - is_open() const - { - return fd_ != -1; - } - - void - close(); - - bool - create (file_mode mode, path_type const& path); - - bool - open (file_mode mode, path_type const& path); - - static - bool - erase (path_type const& path); - - std::size_t - actual_size() const; - - void - read (std::size_t offset, - void* buffer, std::size_t bytes); - - void - write (std::size_t offset, - void const* buffer, std::size_t bytes); - - void - sync(); - - void - trunc (std::size_t length); - -private: - static - std::pair - flags (file_mode mode); -}; - -template -posix_file<_>::~posix_file() -{ - close(); -} - -template -posix_file<_>::posix_file (posix_file &&other) - : fd_ (other.fd_) -{ - other.fd_ = -1; -} - -template -posix_file<_>& -posix_file<_>::operator= (posix_file&& other) -{ - if (&other == this) - return *this; - close(); - fd_ = other.fd_; - other.fd_ = -1; - return *this; -} - -template -void -posix_file<_>::close() -{ - if (fd_ != -1) - { - if (::close(fd_) != 0) - throw file_posix_error( - "close file"); - fd_ = -1; - } -} - -template -bool -posix_file<_>::create (file_mode mode, - path_type const& path) -{ - auto const result = flags(mode); - assert(! is_open()); - fd_ = ::open(path.c_str(), result.first); - if (fd_ != -1) - { - ::close(fd_); - fd_ = -1; - return false; - } - int errnum = errno; - if (errnum != ENOENT) - throw file_posix_error( - "open file", errnum); - fd_ = ::open(path.c_str(), - result.first | O_CREAT, 0644); - if (fd_ == -1) - throw file_posix_error( - "create file"); -#ifndef __APPLE__ - if (::posix_fadvise(fd_, 0, 0, result.second) != 0) - throw file_posix_error( - "fadvise"); -#endif - return true; -} - -template -bool -posix_file<_>::open (file_mode mode, - path_type const& path) -{ - assert(! is_open()); - auto const result = flags(mode); - fd_ = ::open(path.c_str(), result.first); - if (fd_ == -1) - { - int errnum = errno; - if (errnum == ENOENT) - return false; - throw file_posix_error( - "open file", errnum); - } -#ifndef __APPLE__ - if (::posix_fadvise(fd_, 0, 0, result.second) != 0) - throw file_posix_error( - "fadvise"); -#endif - return true; -} - -template -bool -posix_file<_>::erase (path_type const& path) -{ - if (::unlink(path.c_str()) != 0) - { - int const ec = errno; - if (ec != ENOENT) - throw file_posix_error( - "unlink", ec); - return false; - } - return true; -} - -template -std::size_t -posix_file<_>::actual_size() const -{ - struct stat st; - if (::fstat(fd_, &st) != 0) - throw file_posix_error( - "fstat"); - return st.st_size; -} - -template -void -posix_file<_>::read (std::size_t offset, - void* buffer, std::size_t bytes) -{ - while(bytes > 0) - { - auto const n = ::pread ( - fd_, buffer, bytes, offset); - // VFALCO end of file should throw short_read - if (n == -1) - throw file_posix_error( - "pread"); - if (n == 0) - throw file_short_read_error(); - offset += n; - bytes -= n; - buffer = reinterpret_cast< - char*>(buffer) + n; - } -} - -template -void -posix_file<_>::write (std::size_t offset, - void const* buffer, std::size_t bytes) -{ - while(bytes > 0) - { - auto const n = ::pwrite ( - fd_, buffer, bytes, offset); - if (n == -1) - throw file_posix_error( - "pwrite"); - if (n == 0) - throw file_short_write_error(); - offset += n; - bytes -= n; - buffer = reinterpret_cast< - char const*>(buffer) + n; - } -} - -template -void -posix_file<_>::sync() -{ - if (::fsync(fd_) != 0) - throw file_posix_error( - "fsync"); -} - -template -void -posix_file<_>::trunc (std::size_t length) -{ - if (::ftruncate(fd_, length) != 0) - throw file_posix_error( - "ftruncate"); -} - -template -std::pair -posix_file<_>::flags (file_mode mode) -{ - std::pair result; - switch(mode) - { - case file_mode::scan: - result.first = - O_RDONLY; -#ifndef __APPLE__ - result.second = - POSIX_FADV_SEQUENTIAL; -#endif - break; - case file_mode::read: - result.first = - O_RDONLY; -#ifndef __APPLE__ - result.second = - POSIX_FADV_RANDOM; -#endif - break; - case file_mode::append: - result.first = - O_RDWR | - O_APPEND; -#ifndef __APPLE__ - result.second = - POSIX_FADV_RANDOM; -#endif - break; - case file_mode::write: - result.first = - O_RDWR; -#ifndef __APPLE__ - result.second = - POSIX_FADV_NORMAL; -#endif - break; - } - return result; -} - -} // detail - -using posix_file = detail::posix_file<>; - -#endif - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/recover.h b/beast/nudb/recover.h deleted file mode 100644 index cd7847eb1e..0000000000 --- a/beast/nudb/recover.h +++ /dev/null @@ -1,157 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_RECOVER_H_INCLUDED -#define BEAST_NUDB_RECOVER_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { - -/** Perform recovery on a database. - This implements the recovery algorithm by rolling back - any partially committed data. -*/ -template < - class Hasher, - class Codec, - class File = native_file, - class... Args> -bool -recover ( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::size_t read_size, - Args&&... args) -{ - using namespace detail; - File df(args...); - File lf(args...); - File kf(args...); - if (! df.open (file_mode::append, dat_path)) - return false; - if (! kf.open (file_mode::write, key_path)) - return false; - if (! lf.open (file_mode::append, log_path)) - return true; - dat_file_header dh; - key_file_header kh; - log_file_header lh; - try - { - read (kf, kh); - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "short key file header"); - } - // VFALCO should the number of buckets be based on the - // file size in the log record instead? - verify(kh); - try - { - read (df, dh); - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "short data file header"); - } - verify(dh, kh); - auto const lf_size = lf.actual_size(); - if (lf_size == 0) - { - lf.close(); - File::erase (log_path); - return true; - } - try - { - read (lf, lh); - verify(kh, lh); - auto const df_size = df.actual_size(); - buffer buf(kh.block_size); - bucket b (kh.block_size, buf.get()); - bulk_reader r(lf, log_file_header::size, - lf_size, read_size); - while(! r.eof()) - { - std::size_t n; - try - { - // Log Record - auto is = r.prepare(field< - std::uint64_t>::size); - read(is, n); // Index - b.read(r); // Bucket - } - catch (store_corrupt_error const&) - { - throw store_corrupt_error( - "corrupt log record"); - } - catch (file_short_read_error const&) - { - // This means that the log file never - // got fully synced. In which case, there - // were no changes made to the key file. - // So we can recover by just truncating. - break; - } - if (b.spill() && - b.spill() + kh.bucket_size > df_size) - throw store_corrupt_error( - "bad spill in log record"); - // VFALCO is this the right condition? - if (n > kh.buckets) - throw store_corrupt_error( - "bad index in log record"); - b.write (kf, (n + 1) * kh.block_size); - } - kf.trunc(lh.key_file_size); - df.trunc(lh.dat_file_size); - kf.sync(); - df.sync(); - } - catch (file_short_read_error const&) - { - // key and data files should be consistent here - } - - lf.trunc(0); - lf.sync(); - lf.close(); - File::erase (log_path); - return true; -} - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/store.h b/beast/nudb/store.h deleted file mode 100644 index 04917220ef..0000000000 --- a/beast/nudb/store.h +++ /dev/null @@ -1,942 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_STORE_H_INCLUDED -#define BEAST_NUDB_STORE_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if DOXYGEN -#include -#endif - -namespace beast { -namespace nudb { - -/* - - TODO - - - fingerprint / checksum on log records - - - size field at end of data records - allows walking backwards - - - timestamp every so often on data records - allows knowing the age of the data - -*/ - -/** A simple key/value database - @tparam Hasher The hash function to use on key - @tparam Codec The codec to apply to value data - @tparam File The type of File object to use. -*/ -template -class store -{ -public: - using hash_type = Hasher; - using codec_type = Codec; - using file_type = File; - -private: - // requires 64-bit integers or better - static_assert(sizeof(std::size_t)>=8, ""); - - enum - { - // Size of bulk writes - bulk_write_size = 16 * 1024 * 1024, - - // Size of bulk reads during recover - recover_read_size = 16 * 1024 * 1024 - }; - - using clock_type = - std::chrono::steady_clock; - - using shared_lock_type = - boost::shared_lock; - - using unique_lock_type = - boost::unique_lock; - - struct state - { - File df; - File kf; - File lf; - path_type dp; - path_type kp; - path_type lp; - detail::pool p0; - detail::pool p1; - detail::cache c0; - detail::cache c1; - Codec const codec; - detail::key_file_header const kh; - - // pool commit high water mark - std::size_t pool_thresh = 1; - - state (state const&) = delete; - state& operator= (state const&) = delete; - - state (File&& df_, File&& kf_, File&& lf_, - path_type const& dp_, path_type const& kp_, - path_type const& lp_, - detail::key_file_header const& kh_, - std::size_t arena_alloc_size); - }; - - bool open_ = false; - - // VFALCO Unfortunately boost::optional doesn't support - // move construction so we use unique_ptr instead. - std::unique_ptr s_; // State of an open database - - std::size_t frac_; // accumulates load - std::size_t thresh_; // split threshold - std::size_t buckets_; // number of buckets - std::size_t modulus_; // hash modulus - - std::mutex u_; // serializes insert() - detail::gentex g_; - boost::shared_mutex m_; - std::thread thread_; - std::condition_variable_any cond_; - - // These allow insert to block, preventing the pool - // from exceeding a limit. Currently the limit is - // baked in, and can only be reached during sustained - // insertions, such as while importing. - std::size_t commit_limit_ = 1UL * 1024 * 1024 * 1024; - std::condition_variable_any cond_limit_; - - std::atomic epb_; // `true` when ep_ set - std::exception_ptr ep_; - -public: - store() = default; - store (store const&) = delete; - store& operator= (store const&) = delete; - - /** Destroy the database. - - Files are closed, memory is freed, and data that has not been - committed is discarded. To ensure that all inserted data is - written, it is necessary to call close() before destroying the - store. - - This function catches all exceptions thrown by callees, so it - will be necessary to call close() before destroying the store - if callers want to catch exceptions. - - Throws: - None - */ - ~store(); - - /** Returns `true` if the database is open. */ - bool - is_open() const - { - return open_; - } - - path_type const& - dat_path() const - { - return s_->dp; - } - - path_type const& - key_path() const - { - return s_->kp; - } - - path_type const& - log_path() const - { - return s_->lp; - } - - std::uint64_t - appnum() const - { - return s_->kh.appnum; - } - - /** Close the database. - - All data is committed before closing. - - Throws: - store_error - */ - void - close(); - - /** Open a database. - - @param args Arguments passed to File constructors - @return `true` if each file could be opened - */ - template - bool - open ( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::size_t arena_alloc_size, - Args&&... args); - - /** Fetch a value. - - If key is found, Handler will be called as: - `(void)()(void const* data, std::size_t size)` - - where data and size represent the value. If the - key is not found, the handler is not called. - - @return `true` if a matching key was found. - */ - template - bool - fetch (void const* key, Handler&& handler); - - /** Insert a value. - - Returns: - `true` if the key was inserted, - `false` if the key already existed - */ - bool - insert (void const* key, void const* data, - std::size_t bytes); - -private: - void - rethrow() - { - if (epb_.load()) - std::rethrow_exception(ep_); - } - - // Fetch key in loaded bucket b or its spills. - // - template - bool - fetch (std::size_t h, void const* key, - detail::bucket b, Handler&& handler); - - // Returns `true` if the key exists - // lock is unlocked after the first bucket processed - // - bool - exists (std::size_t h, void const* key, - shared_lock_type* lock, detail::bucket b); - - void - split (detail::bucket& b1, detail::bucket& b2, - detail::bucket& tmp, std::size_t n1, std::size_t n2, - std::size_t buckets, std::size_t modulus, - detail::bulk_writer& w); - - detail::bucket - load (std::size_t n, detail::cache& c1, - detail::cache& c0, void* buf); - - void - commit(); - - void - run(); -}; - -//------------------------------------------------------------------------------ - -template -store::state::state ( - File&& df_, File&& kf_, File&& lf_, - path_type const& dp_, path_type const& kp_, - path_type const& lp_, - detail::key_file_header const& kh_, - std::size_t arena_alloc_size) - : df (std::move(df_)) - , kf (std::move(kf_)) - , lf (std::move(lf_)) - , dp (dp_) - , kp (kp_) - , lp (lp_) - , p0 (kh_.key_size, arena_alloc_size) - , p1 (kh_.key_size, arena_alloc_size) - , c0 (kh_.key_size, kh_.block_size) - , c1 (kh_.key_size, kh_.block_size) - , kh (kh_) -{ -} - -//------------------------------------------------------------------------------ - -template -store::~store() -{ - try - { - close(); - } - catch (...) - { - // If callers want to see the exceptions - // they have to call close manually. - } -} - -template -template -bool -store::open ( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::size_t arena_alloc_size, - Args&&... args) -{ - using namespace detail; - if (is_open()) - throw std::logic_error("nudb: already open"); - epb_.store(false); - recover( - dat_path, key_path, log_path, - recover_read_size, - args...); - File df(args...); - File kf(args...); - File lf(args...); - if (! df.open (file_mode::append, dat_path)) - return false; - if (! kf.open (file_mode::write, key_path)) - return false; - if (! lf.create (file_mode::append, log_path)) - return false; - dat_file_header dh; - key_file_header kh; - read (df, dh); - read (kf, kh); - verify (dh); - verify (kh); - verify (dh, kh); - auto s = std::make_unique( - std::move(df), std::move(kf), std::move(lf), - dat_path, key_path, log_path, kh, - arena_alloc_size); - thresh_ = std::max(65536UL, - kh.load_factor * kh.capacity); - frac_ = thresh_ / 2; - buckets_ = kh.buckets; - modulus_ = ceil_pow2(kh.buckets); - // VFALCO TODO This could be better - if (buckets_ < 1) - throw store_corrupt_error ( - "bad key file length"); - s_ = std::move(s); - open_ = true; - thread_ = std::thread( - &store::run, this); - return true; -} - -template -void -store::close() -{ - if (open_) - { - // Set this first otherwise a - // throw can cause another close(). - open_ = false; - cond_.notify_all(); - thread_.join(); - rethrow(); - s_->lf.close(); - File::erase(s_->lp); - s_.reset(); - } -} - -template -template -bool -store::fetch ( - void const* key, Handler&& handler) -{ - using namespace detail; - rethrow(); - auto const h = hash( - key, s_->kh.key_size, s_->kh.salt); - shared_lock_type m (m_); - { - auto iter = s_->p1.find(key); - if (iter == s_->p1.end()) - { - iter = s_->p0.find(key); - if (iter == s_->p0.end()) - goto next; - } - buffer buf; - auto const result = - s_->codec.decompress( - iter->first.data, - iter->first.size, buf); - handler(result.first, result.second); - return true; - } -next: - auto const n = bucket_index( - h, buckets_, modulus_); - auto const iter = s_->c1.find(n); - if (iter != s_->c1.end()) - return fetch(h, key, - iter->second, handler); - // VFALCO Audit for concurrency - genlock g (g_); - m.unlock(); - buffer buf (s_->kh.block_size); - // VFALCO Constructs with garbage here - bucket b (s_->kh.block_size, - buf.get()); - b.read (s_->kf, - (n + 1) * b.block_size()); - return fetch(h, key, b, handler); -} - -template -bool -store::insert ( - void const* key, void const* data, - std::size_t size) -{ - using namespace detail; - rethrow(); - buffer buf; - // Data Record - if (size > field::max) - throw std::logic_error( - "nudb: size too large"); - auto const h = hash( - key, s_->kh.key_size, s_->kh.salt); - std::lock_guard u (u_); - { - shared_lock_type m (m_); - if (s_->p1.find(key) != s_->p1.end()) - return false; - if (s_->p0.find(key) != s_->p0.end()) - return false; - auto const n = bucket_index( - h, buckets_, modulus_); - auto const iter = s_->c1.find(n); - if (iter != s_->c1.end()) - { - if (exists(h, key, &m, - iter->second)) - return false; - // m is now unlocked - } - else - { - // VFALCO Audit for concurrency - genlock g (g_); - m.unlock(); - buf.reserve(s_->kh.block_size); - bucket b (s_->kh.block_size, - buf.get()); - b.read (s_->kf, - (n + 1) * s_->kh.block_size); - if (exists(h, key, nullptr, b)) - return false; - } - } - auto const result = - s_->codec.compress(data, size, buf); - // Perform insert - unique_lock_type m (m_); - s_->p1.insert (h, key, - result.first, result.second); - // Did we go over the commit limit? - if (commit_limit_ > 0 && - s_->p1.data_size() >= commit_limit_) - { - // Yes, start a new commit - cond_.notify_all(); - // Wait for pool to shrink - cond_limit_.wait(m, - [this]() { return - s_->p1.data_size() < - commit_limit_; }); - } - bool const notify = - s_->p1.data_size() >= s_->pool_thresh; - m.unlock(); - if (notify) - cond_.notify_all(); - return true; -} - -template -template -bool -store::fetch ( - std::size_t h, void const* key, - detail::bucket b, Handler&& handler) -{ - using namespace detail; - buffer buf0; - buffer buf1; - for(;;) - { - for (auto i = b.lower_bound(h); - i < b.size(); ++i) - { - auto const item = b[i]; - if (item.hash != h) - break; - // Data Record - auto const len = - s_->kh.key_size + // Key - item.size; // Value - buf0.reserve(len); - s_->df.read(item.offset + - field::size, // Size - buf0.get(), len); - if (std::memcmp(buf0.get(), key, - s_->kh.key_size) == 0) - { - auto const result = - s_->codec.decompress( - buf0.get() + s_->kh.key_size, - item.size, buf1); - handler(result.first, result.second); - return true; - } - } - auto const spill = b.spill(); - if (! spill) - break; - buf1.reserve(s_->kh.block_size); - b = bucket(s_->kh.block_size, - buf1.get()); - b.read(s_->df, spill); - } - return false; -} - -template -bool -store::exists ( - std::size_t h, void const* key, - shared_lock_type* lock, detail::bucket b) -{ - using namespace detail; - buffer buf(s_->kh.key_size + - s_->kh.block_size); - void* pk = buf.get(); - void* pb = buf.get() + s_->kh.key_size; - for(;;) - { - for (auto i = b.lower_bound(h); - i < b.size(); ++i) - { - auto const item = b[i]; - if (item.hash != h) - break; - // Data Record - s_->df.read(item.offset + - field::size, // Size - pk, s_->kh.key_size); // Key - if (std::memcmp(pk, key, - s_->kh.key_size) == 0) - return true; - } - auto spill = b.spill(); - if (lock && lock->owns_lock()) - lock->unlock(); - if (! spill) - break; - b = bucket(s_->kh.block_size, pb); - b.read(s_->df, spill); - } - return false; -} - -// Split the bucket in b1 to b2 -// b1 must be loaded -// tmp is used as a temporary buffer -// splits are written but not the new buckets -// -template -void -store::split (detail::bucket& b1, - detail::bucket& b2, detail::bucket& tmp, - std::size_t n1, std::size_t n2, - std::size_t buckets, std::size_t modulus, - detail::bulk_writer& w) -{ - using namespace detail; - // Trivial case: split empty bucket - if (b1.empty()) - return; - // Split - for (std::size_t i = 0; i < b1.size();) - { - auto const e = b1[i]; - auto const n = bucket_index( - e.hash, buckets, modulus); - assert(n==n1 || n==n2); - if (n == n2) - { - b2.insert (e.offset, e.size, e.hash); - b1.erase (i); - } - else - { - ++i; - } - } - std::size_t spill = b1.spill(); - if (spill) - { - b1.spill (0); - do - { - // If any part of the spill record is - // in the write buffer then flush first - // VFALCO Needs audit - if (spill + bucket_size(s_->kh.capacity) > - w.offset() - w.size()) - w.flush(); - tmp.read (s_->df, spill); - for (std::size_t i = 0; i < tmp.size(); ++i) - { - auto const e = tmp[i]; - auto const n = bucket_index( - e.hash, buckets, modulus); - assert(n==n1 || n==n2); - if (n == n2) - { - maybe_spill(b2, w); - b2.insert( - e.offset, e.size, e.hash); - } - else - { - maybe_spill(b1, w); - b1.insert( - e.offset, e.size, e.hash); - } - } - spill = tmp.spill(); - } - while (spill); - } -} - -// Effects: -// -// Returns a bucket from caches or the key file -// -// If the bucket is found in c1, returns the -// bucket from c1. -// Else if the bucket number is greater than buckets(), -// throws. -// Else, If the bucket is found in c2, inserts the -// bucket into c1 and returns the bucket from c1. -// Else, reads the bucket from the key file, inserts -// the bucket into c0 and c1, and returns -// the bucket from c1. -// -// Preconditions: -// buf points to a buffer of at least block_size() bytes -// -// Postconditions: -// c1, and c0, and the memory pointed to by buf may be modified -// -template -detail::bucket -store::load ( - std::size_t n, detail::cache& c1, - detail::cache& c0, void* buf) -{ - using namespace detail; - auto iter = c1.find(n); - if (iter != c1.end()) - return iter->second; - iter = c0.find(n); - if (iter != c0.end()) - return c1.insert (n, - iter->second)->second; - bucket tmp (s_->kh.block_size, buf); - tmp.read (s_->kf, (n + 1) * - s_->kh.block_size); - c0.insert (n, tmp); - return c1.insert (n, tmp)->second; -} - -// Commit the memory pool to disk, then sync. -// -// Preconditions: -// -// Effects: -// -template -void -store::commit() -{ - using namespace detail; - buffer buf1 (s_->kh.block_size); - buffer buf2 (s_->kh.block_size); - bucket tmp (s_->kh.block_size, buf1.get()); - // Empty cache put in place temporarily - // so we can reuse the memory from s_->c1 - cache c1; - { - unique_lock_type m (m_); - if (s_->p1.empty()) - return; - if (s_->p1.data_size() >= commit_limit_) - cond_limit_.notify_all(); - swap (s_->c1, c1); - swap (s_->p0, s_->p1); - s_->pool_thresh = std::max( - s_->pool_thresh, s_->p0.data_size()); - m.unlock(); - } - // Prepare rollback information - // Log File Header - log_file_header lh; - lh.version = currentVersion; // Version - lh.uid = s_->kh.uid; // UID - lh.appnum = s_->kh.appnum; // Appnum - lh.key_size = s_->kh.key_size; // Key Size - lh.salt = s_->kh.salt; // Salt - lh.pepper = pepper( - lh.salt); // Pepper - lh.block_size = - s_->kh.block_size; // Block Size - lh.key_file_size = - s_->kf.actual_size(); // Key File Size - lh.dat_file_size = - s_->df.actual_size(); // Data File Size - write (s_->lf, lh); - s_->lf.sync(); - // Append data and spills to data file - auto modulus = modulus_; - auto buckets = buckets_; - { - // Bulk write to avoid write amplification - bulk_writer w (s_->df, - s_->df.actual_size(), bulk_write_size); - // Write inserted data to the data file - for (auto& e : s_->p0) - { - // VFALCO This could be UB since other - // threads are reading other data members - // of this object in memory - e.second = w.offset(); - auto os = w.prepare (value_size( - e.first.size, s_->kh.key_size)); - // Data Record - write (os, - e.first.size); // Size - write (os, e.first.key, - s_->kh.key_size); // Key - write (os, e.first.data, - e.first.size); // Data - } - // Do inserts, splits, and build view - // of original and modified buckets - for (auto const e : s_->p0) - { - // VFALCO Should this be >= or > ? - if ((frac_ += 65536) >= thresh_) - { - // split - frac_ -= thresh_; - if (buckets == modulus) - modulus *= 2; - auto const n1 = buckets - (modulus / 2); - auto const n2 = buckets++; - auto b1 = load (n1, c1, s_->c0, buf2.get()); - auto b2 = c1.create (n2); - // If split spills, the writer is - // flushed which can amplify writes. - split (b1, b2, tmp, n1, n2, - buckets, modulus, w); - } - // insert - auto const n = bucket_index( - e.first.hash, buckets, modulus); - auto b = load (n, c1, s_->c0, buf2.get()); - // This can amplify writes if it spills. - maybe_spill(b, w); - b.insert (e.second, - e.first.size, e.first.hash); - } - w.flush(); - } - // Give readers a view of the new buckets. - // This might be slightly better than the old - // view since there could be fewer spills. - { - unique_lock_type m (m_); - swap(c1, s_->c1); - s_->p0.clear(); - buckets_ = buckets; - modulus_ = modulus; - g_.start(); - } - // Write clean buckets to log file - // VFALCO Should the bulk_writer buffer size be tunable? - { - bulk_writer w(s_->lf, - s_->lf.actual_size(), bulk_write_size); - for (auto const e : s_->c0) - { - // Log Record - auto os = w.prepare( - field::size + // Index - e.second.compact_size()); // Bucket - // Log Record - write(os, e.first); // Index - e.second.write(os); // Bucket - } - s_->c0.clear(); - w.flush(); - s_->lf.sync(); - } - g_.finish(); - // Write new buckets to key file - for (auto const e : s_->c1) - e.second.write (s_->kf, - (e.first + 1) * s_->kh.block_size); - // Finalize the commit - s_->df.sync(); - s_->kf.sync(); - s_->lf.trunc(0); - s_->lf.sync(); - // Cache is no longer needed, all fetches will go straight - // to disk again. Do this after the sync, otherwise readers - // might get blocked longer due to the extra I/O. - // VFALCO is this correct? - { - unique_lock_type m (m_); - s_->c1.clear(); - } -} - -template -void -store::run() -{ - auto const pred = - [this]() - { - return - ! open_ || - s_->p1.data_size() >= - s_->pool_thresh || - s_->p1.data_size() >= - commit_limit_; - }; - try - { - while (open_) - { - for(;;) - { - using std::chrono::seconds; - unique_lock_type m (m_); - bool const timeout = - ! cond_.wait_for (m, - seconds(1), pred); - if (! open_) - break; - m.unlock(); - commit(); - // Reclaim some memory if - // we get a spare moment. - if (timeout) - { - m.lock(); - s_->pool_thresh = - std::max( - 1, s_->pool_thresh / 2); - s_->p1.shrink_to_fit(); - s_->p0.shrink_to_fit(); - s_->c1.shrink_to_fit(); - s_->c0.shrink_to_fit(); - m.unlock(); - } - } - } - commit(); - } - catch(...) - { - ep_ = std::current_exception(); // must come first - epb_.store(true); - } -} - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/tests/callgrind_test.cpp b/beast/nudb/tests/callgrind_test.cpp deleted file mode 100644 index d761c2cf7e..0000000000 --- a/beast/nudb/tests/callgrind_test.cpp +++ /dev/null @@ -1,111 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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 -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace test { - -// This test is designed for callgrind runs to find hotspots -class callgrind_test : public unit_test::suite -{ -public: - // Creates and opens a database, performs a bunch - // of inserts, then alternates fetching all the keys - // with keys not present. - void - do_test (std::size_t count, - path_type const& path) - { - auto const dp = path + ".dat"; - auto const kp = path + ".key"; - auto const lp = path + ".log"; - test_api::create (dp, kp, lp, - appnum, - salt, - sizeof(nudb::test::key_type), - nudb::block_size(path), - 0.50); - test_api::store db; - if (! expect (db.open(dp, kp, lp, - arena_alloc_size), "open")) - return; - expect (db.appnum() == appnum, "appnum"); - Sequence seq; - for (std::size_t i = 0; i < count; ++i) - { - auto const v = seq[i]; - expect (db.insert(&v.key, v.data, v.size), - "insert"); - } - Storage s; - for (std::size_t i = 0; i < count * 2; ++i) - { - if (! (i%2)) - { - auto const v = seq[i/2]; - expect (db.fetch (&v.key, s), "fetch"); - expect (s.size() == v.size, "size"); - expect (std::memcmp(s.get(), - v.data, v.size) == 0, "data"); - } - else - { - auto const v = seq[count + i/2]; - expect (! db.fetch (&v.key, s), - "fetch missing"); - } - } - db.close(); - nudb::native_file::erase (dp); - nudb::native_file::erase (kp); - nudb::native_file::erase (lp); - } - - void - run() override - { - enum - { - // higher numbers, more pain - N = 100000 - }; - - testcase (abort_on_fail); - - beast::UnitTestUtilities::TempDirectory tempDir; - do_test (N, tempDir.path()); - } -}; - -BEAST_DEFINE_TESTSUITE_MANUAL(callgrind,nudb,beast); - -} // test -} // nudb -} // beast - diff --git a/beast/nudb/tests/common.h b/beast/nudb/tests/common.h deleted file mode 100644 index 1930d457b3..0000000000 --- a/beast/nudb/tests/common.h +++ /dev/null @@ -1,259 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_TESTS_COMMON_H_INCLUDED -#define BEAST_NUDB_TESTS_COMMON_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace test { - -using key_type = std::size_t; - -// xxhasher is fast and produces good results -using test_api_base = - nudb::api; - -struct test_api : test_api_base -{ - using fail_store = nudb::store< - typename test_api_base::hash_type, - typename test_api_base::codec_type, - nudb::fail_file >; -}; - -static std::size_t BEAST_CONSTEXPR arena_alloc_size = 16 * 1024 * 1024; - -static std::uint64_t BEAST_CONSTEXPR appnum = 1337; - -static std::uint64_t BEAST_CONSTEXPR salt = 42; - -//------------------------------------------------------------------------------ - -// Meets the requirements of Handler -class Storage -{ -private: - std::size_t size_ = 0; - std::size_t capacity_ = 0; - std::unique_ptr buf_; - -public: - Storage() = default; - Storage (Storage const&) = delete; - Storage& operator= (Storage const&) = delete; - - std::size_t - size() const - { - return size_; - } - - std::uint8_t* - get() const - { - return buf_.get(); - } - - std::uint8_t* - reserve (std::size_t size) - { - if (capacity_ < size) - { - capacity_ = detail::ceil_pow2(size); - buf_.reset ( - new std::uint8_t[capacity_]); - } - size_ = size; - return buf_.get(); - } - - std::uint8_t* - operator()(void const* data, std::size_t size) - { - reserve (size); - std::memcpy(buf_.get(), data, size); - return buf_.get(); - } -}; - -struct value_type -{ - value_type() = default; - value_type (value_type const&) = default; - value_type& operator= (value_type const&) = default; - - key_type key; - std::size_t size; - uint8_t* data; -}; - -//------------------------------------------------------------------------------ - -template -static -void -rngcpy (void* buffer, std::size_t bytes, - Generator& g) -{ - using result_type = - typename Generator::result_type; - while (bytes >= sizeof(result_type)) - { - auto const v = g(); - memcpy(buffer, &v, sizeof(v)); - buffer = reinterpret_cast< - std::uint8_t*>(buffer) + sizeof(v); - bytes -= sizeof(v); - } - if (bytes > 0) - { - auto const v = g(); - memcpy(buffer, &v, bytes); - } -} - -//------------------------------------------------------------------------------ - -class Sequence -{ -public: - using key_type = test::key_type; - -private: - enum - { - minSize = 250, - maxSize = 1250 - }; - - Storage s_; - beast::xor_shift_engine gen_; - std::uniform_int_distribution d_size_; - -public: - Sequence() - : d_size_ (minSize, maxSize) - { - } - - // Returns the n-th key - key_type - key (std::size_t n) - { - gen_.seed(n+1); - key_type result; - rngcpy (&result, sizeof(result), gen_); - return result; - } - - // Returns the n-th value - value_type - operator[] (std::size_t n) - { - gen_.seed(n+1); - value_type v; - rngcpy (&v.key, sizeof(v.key), gen_); - v.size = d_size_(gen_); - v.data = s_.reserve(v.size); - rngcpy (v.data, v.size, gen_); - return v; - } -}; - -template -static -std::string -num (T t) -{ - std::string s = std::to_string(t); - std::reverse(s.begin(), s.end()); - std::string s2; - s2.reserve(s.size() + (s.size()+2)/3); - int n = 0; - for (auto c : s) - { - if (n == 3) - { - n = 0; - s2.insert (s2.begin(), ','); - } - ++n; - s2.insert(s2.begin(), c); - } - return s2; -} - -template -void -print (Log log, - beast::nudb::verify_info const& info) -{ - log << "avg_fetch: " << std::fixed << std::setprecision(3) << - info.avg_fetch; - log << "waste: " << std::fixed << std::setprecision(3) << - info.waste * 100 << "%"; - log << "overhead: " << std::fixed << std::setprecision(1) << - info.overhead * 100 << "%"; - log << "actual_load: " << std::fixed << std::setprecision(0) << - info.actual_load * 100 << "%"; - log << "version: " << num(info.version); - log << "uid: " << std::showbase << std::hex << info.uid; - log << "appnum: " << info.appnum; - log << "key_size: " << num(info.key_size); - log << "salt: " << std::showbase << std::hex << info.salt; - log << "pepper: " << std::showbase << std::hex << info.pepper; - log << "block_size: " << num(info.block_size); - log << "bucket_size: " << num(info.bucket_size); - log << "load_factor: " << std::fixed << std::setprecision(0) << - info.load_factor * 100 << "%"; - log << "capacity: " << num(info.capacity); - log << "buckets: " << num(info.buckets); - log << "key_count: " << num(info.key_count); - log << "value_count: " << num(info.value_count); - log << "value_bytes: " << num(info.value_bytes); - log << "spill_count: " << num(info.spill_count); - log << "spill_count_tot: " << num(info.spill_count_tot); - log << "spill_bytes: " << num(info.spill_bytes); - log << "spill_bytes_tot: " << num(info.spill_bytes_tot); - log << "key_file_size: " << num(info.key_file_size); - log << "dat_file_size: " << num(info.dat_file_size); - - std::string s; - for (int i = 0; i < info.hist.size(); ++i) - s += (i==0) ? - std::to_string(info.hist[i]) : - (", " + std::to_string(info.hist[i])); - log << "hist: " << s; -} - -} // test -} // nudb -} // beast - -#endif diff --git a/beast/nudb/tests/fail_file.h b/beast/nudb/tests/fail_file.h deleted file mode 100644 index fae4cf1623..0000000000 --- a/beast/nudb/tests/fail_file.h +++ /dev/null @@ -1,245 +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_NUDB_FAIL_FILE_H_INCLUDED -#define BEAST_NUDB_FAIL_FILE_H_INCLUDED - -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { - -/** Thrown when a test failure mode occurs. */ -struct fail_error : std::exception -{ - char const* - what() const noexcept override - { - return "test failure"; - } -}; - -/** Countdown to test failure modue. */ -class fail_counter -{ -private: - std::size_t target_; - std::atomic count_; - -public: - fail_counter (fail_counter const&) = delete; - fail_counter& operator= (fail_counter const&) = delete; - - explicit - fail_counter (std::size_t target = 0) - { - reset (target); - } - - /** Reset the counter to fail at the nth step, or 0 for no failure. */ - void - reset (std::size_t n = 0) - { - target_ = n; - count_.store(0); - } - - bool - fail() - { - return target_ && (++count_ >= target_); - } -}; - -/** Wrapper to simulate file system failures. */ -template -class fail_file -{ -private: - File f_; - fail_counter* c_ = nullptr; - -public: - fail_file() = default; - fail_file (fail_file const&) = delete; - fail_file& operator= (fail_file const&) = delete; - ~fail_file() = default; - - fail_file (fail_file&&); - - fail_file& - operator= (fail_file&& other); - - explicit - fail_file (fail_counter& c); - - bool - is_open() const - { - return f_.is_open(); - } - - path_type const& - path() const - { - return f_.path(); - } - - std::size_t - actual_size() const - { - return f_.actual_size(); - } - - void - close() - { - f_.close(); - } - - bool - create (file_mode mode, - path_type const& path) - { - return f_.create(mode, path); - } - - bool - open (file_mode mode, - path_type const& path) - { - return f_.open(mode, path); - } - - static - void - erase (path_type const& path) - { - File::erase(path); - } - - void - read (std::size_t offset, - void* buffer, std::size_t bytes) - { - f_.read(offset, buffer, bytes); - } - - void - write (std::size_t offset, - void const* buffer, std::size_t bytes); - - void - sync(); - - void - trunc (std::size_t length); - -private: - bool - fail(); - - void - do_fail(); -}; - -template -fail_file::fail_file (fail_file&& other) - : f_ (std::move(other.f_)) - , c_ (other.c_) -{ - other.c_ = nullptr; -} - -template -fail_file& -fail_file::operator= (fail_file&& other) -{ - f_ = std::move(other.f_); - c_ = other.c_; - other.c_ = nullptr; - return *this; -} - -template -fail_file::fail_file (fail_counter& c) - : c_ (&c) -{ -} - -template -void -fail_file::write (std::size_t offset, - void const* buffer, std::size_t bytes) -{ - if (fail()) - do_fail(); - if (fail()) - { - f_.write(offset, buffer, (bytes + 1) / 2); - do_fail(); - } - f_.write(offset, buffer, bytes); -} - -template -void -fail_file::sync() -{ - if (fail()) - do_fail(); - // We don't need a real sync for - // testing, it just slows things down. - //f_.sync(); -} - -template -void -fail_file::trunc (std::size_t length) -{ - if (fail()) - do_fail(); - f_.trunc(length); -} - -template -bool -fail_file::fail() -{ - if (c_) - return c_->fail(); - return false; -} - -template -void -fail_file::do_fail() -{ - throw fail_error(); -} - -} -} - -#endif - diff --git a/beast/nudb/tests/recover_test.cpp b/beast/nudb/tests/recover_test.cpp deleted file mode 100644 index 45fd12ea11..0000000000 --- a/beast/nudb/tests/recover_test.cpp +++ /dev/null @@ -1,180 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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 -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace test { - -class basic_recover_test : public unit_test::suite -{ -public: - // Creates and opens a database, performs a bunch - // of inserts, then fetches all of them to make sure - // they are there. Uses a fail_file that causes the n-th - // I/O to fail, causing an exception. - void - do_work (std::size_t count, float load_factor, - nudb::path_type const& path, fail_counter& c) - { - auto const dp = path + ".dat"; - auto const kp = path + ".key"; - auto const lp = path + ".log"; - test_api::file_type::erase (dp); - test_api::file_type::erase (kp); - test_api::file_type::erase (lp); - expect(test_api::create ( - dp, kp, lp, appnum, salt, sizeof(key_type), - block_size(path), load_factor), "create"); - test_api::fail_store db; - if (! expect(db.open(dp, kp, lp, - arena_alloc_size, c), "open")) - { - // VFALCO open should never fail here, we need - // to report this and terminate the test. - } - expect (db.appnum() == appnum, "appnum"); - Sequence seq; - for (std::size_t i = 0; i < count; ++i) - { - auto const v = seq[i]; - expect(db.insert(&v.key, v.data, v.size), - "insert"); - } - Storage s; - for (std::size_t i = 0; i < count; ++i) - { - auto const v = seq[i]; - if (! expect(db.fetch (&v.key, s), - "fetch")) - break; - if (! expect(s.size() == v.size, "size")) - break; - if (! expect(std::memcmp(s.get(), - v.data, v.size) == 0, "data")) - break; - } - db.close(); - verify_info info; - try - { - info = test_api::verify(dp, kp); - } - catch(...) - { - print(log, info); - throw; - } - test_api::file_type::erase (dp); - test_api::file_type::erase (kp); - test_api::file_type::erase (lp); - } - - void - do_recover (path_type const& path, - fail_counter& c) - { - auto const dp = path + ".dat"; - auto const kp = path + ".key"; - auto const lp = path + ".log"; - recover>(dp, kp, lp, - test_api::buffer_size, c); - test_api::verify(dp, kp); - test_api::file_type::erase (dp); - test_api::file_type::erase (kp); - test_api::file_type::erase (lp); - } - - void - test_recover (float load_factor, std::size_t count) - { - testcase << count << " inserts"; - - beast::UnitTestUtilities::TempDirectory tempDir; - - auto const path = tempDir.path(); - for (std::size_t n = 1;;++n) - { - try - { - fail_counter c(n); - do_work (count, load_factor, path, c); - break; - } - catch (nudb::fail_error const&) - { - } - for (std::size_t m = 1;;++m) - { - fail_counter c(m); - try - { - do_recover (path, c); - break; - } - catch (nudb::fail_error const&) - { - } - } - } - } -}; - -class recover_test : public basic_recover_test -{ -public: - void - run() override - { - float lf = 0.55f; - test_recover (lf, 0); - test_recover (lf, 10); - test_recover (lf, 100); - } -}; - -BEAST_DEFINE_TESTSUITE(recover,nudb,beast); - -class recover_big_test : public basic_recover_test -{ -public: - void - run() override - { - float lf = 0.90f; - test_recover (lf, 1000); - test_recover (lf, 10000); - test_recover (lf, 100000); - } -}; - -} // test -} // nudb -} // beast - diff --git a/beast/nudb/tests/store_test.cpp b/beast/nudb/tests/store_test.cpp deleted file mode 100644 index 12d55fd852..0000000000 --- a/beast/nudb/tests/store_test.cpp +++ /dev/null @@ -1,144 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace test { - -// Basic, single threaded test that verifies the -// correct operation of the store. Load factor is -// set high to ensure that spill records are created, -// exercised, and split. -// -class store_test : public unit_test::suite -{ -public: - void - do_test (std::size_t N, - std::size_t block_size, float load_factor) - { - testcase (abort_on_fail); - beast::UnitTestUtilities::TempDirectory tempDir; - - auto const dp = tempDir.file ("nudb.dat"); - auto const kp = tempDir.file ("nudb.key"); - auto const lp = tempDir.file ("nudb.log"); - Sequence seq; - test_api::store db; - try - { - expect (test_api::create (dp, kp, lp, appnum, - salt, sizeof(key_type), block_size, - load_factor), "create"); - expect (db.open(dp, kp, lp, - arena_alloc_size), "open"); - Storage s; - // insert - for (std::size_t i = 0; i < N; ++i) - { - auto const v = seq[i]; - expect (db.insert( - &v.key, v.data, v.size), "insert 1"); - } - // fetch - for (std::size_t i = 0; i < N; ++i) - { - auto const v = seq[i]; - bool const found = db.fetch (&v.key, s); - expect (found, "not found"); - expect (s.size() == v.size, "wrong size"); - expect (std::memcmp(s.get(), - v.data, v.size) == 0, "not equal"); - } - // insert duplicates - for (std::size_t i = 0; i < N; ++i) - { - auto const v = seq[i]; - expect (! db.insert(&v.key, - v.data, v.size), "insert duplicate"); - } - // insert/fetch - for (std::size_t i = 0; i < N; ++i) - { - auto v = seq[i]; - bool const found = db.fetch (&v.key, s); - expect (found, "missing"); - expect (s.size() == v.size, "wrong size"); - expect (memcmp(s.get(), - v.data, v.size) == 0, "wrong data"); - v = seq[i + N]; - expect (db.insert(&v.key, v.data, v.size), - "insert 2"); - } - db.close(); - //auto const stats = test_api::verify(dp, kp); - auto const stats = verify( - dp, kp, 1 * 1024 * 1024); - expect (stats.hist[1] > 0, "no splits"); - print (log, stats); - } - catch (nudb::store_error const& e) - { - fail (e.what()); - } - catch (std::exception const& e) - { - fail (e.what()); - } - expect (test_api::file_type::erase(dp)); - expect (test_api::file_type::erase(kp)); - expect (! test_api::file_type::erase(lp)); - } - - void - run() override - { - enum - { - #ifndef NDEBUG - N = 5000 // debug - #else - N = 50000 - #endif - ,block_size = 256 - }; - - float const load_factor = 0.95f; - - do_test (N, block_size, load_factor); - } -}; - -BEAST_DEFINE_TESTSUITE(store,nudb,beast); - -} // test -} // nudb -} // beast - diff --git a/beast/nudb/tests/varint_test.cpp b/beast/nudb/tests/varint_test.cpp deleted file mode 100644 index 9aab351071..0000000000 --- a/beast/nudb/tests/varint_test.cpp +++ /dev/null @@ -1,73 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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 -#include -#include - -namespace beast { -namespace nudb { -namespace tests { - -class varint_test : public unit_test::suite -{ -public: - void - test_varints (std::vector vv) - { - testcase("encode, decode"); - for (auto const v : vv) - { - std::array::max> vi; - auto const n0 = - detail::write_varint( - vi.data(), v); - expect (n0 > 0, "write error"); - std::size_t v1; - auto const n1 = - detail::read_varint( - vi.data(), n0, v1); - expect(n1 == n0, "read error"); - expect(v == v1, "wrong value"); - } - } - - void - run() override - { - test_varints({ - 0, 1, 2, - 126, 127, 128, - 253, 254, 255, - 16127, 16128, 16129, - 0xff, - 0xffff, - 0xffffffff, - 0xffffffffffffUL, - 0xffffffffffffffffUL}); - } -}; - -BEAST_DEFINE_TESTSUITE(varint,nudb,beast); - -} // test -} // nudb -} // beast diff --git a/beast/nudb/tests/verify_test.cpp b/beast/nudb/tests/verify_test.cpp deleted file mode 100644 index f6f5e71010..0000000000 --- a/beast/nudb/tests/verify_test.cpp +++ /dev/null @@ -1,286 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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 -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { -namespace test { - -namespace detail { - -class save_stream_state -{ - std::ostream& os_; - std::streamsize precision_; - std::ios::fmtflags flags_; - std::ios::char_type fill_; -public: - ~save_stream_state() - { - os_.precision(precision_); - os_.flags(flags_); - os_.fill(fill_); - } - save_stream_state(save_stream_state const&) = delete; - save_stream_state& operator=(save_stream_state const&) = delete; - explicit save_stream_state(std::ostream& os) - : os_(os) - , precision_(os.precision()) - , flags_(os.flags()) - , fill_(os.fill()) - { - } -}; - -template -std::ostream& -pretty_time(std::ostream& os, std::chrono::duration d) -{ - save_stream_state _(os); - using namespace std::chrono; - if (d < microseconds{1}) - { - // use nanoseconds - if (d < nanoseconds{100}) - { - // use floating - using ns = duration; - os << std::fixed << std::setprecision(1) << ns(d).count(); - } - else - { - // use integral - os << std::chrono::duration_cast(d).count(); - } - os << "ns"; - } - else if (d < milliseconds{1}) - { - // use microseconds - if (d < microseconds{100}) - { - // use floating - using ms = duration; - os << std::fixed << std::setprecision(1) << ms(d).count(); - } - else - { - // use integral - os << std::chrono::duration_cast(d).count(); - } - os << "us"; - } - else if (d < seconds{1}) - { - // use milliseconds - if (d < milliseconds{100}) - { - // use floating - using ms = duration; - os << std::fixed << std::setprecision(1) << ms(d).count(); - } - else - { - // use integral - os << std::chrono::duration_cast(d).count(); - } - os << "ms"; - } - else if (d < minutes{1}) - { - // use seconds - if (d < seconds{100}) - { - // use floating - using s = duration; - os << std::fixed << std::setprecision(1) << s(d).count(); - } - else - { - // use integral - os << std::chrono::duration_cast(d).count(); - } - os << "s"; - } - else - { - // use minutes - if (d < minutes{100}) - { - // use floating - using m = duration>; - os << std::fixed << std::setprecision(1) << m(d).count(); - } - else - { - // use integral - os << std::chrono::duration_cast(d).count(); - } - os << "min"; - } - return os; -} - -template -inline -std::string -fmtdur(std::chrono::duration const& d) -{ - std::stringstream ss; - pretty_time(ss, d); - return ss.str(); -} - -} // detail - -//------------------------------------------------------------------------------ - -template -class progress -{ -private: - using clock_type = - beast::basic_seconds_clock< - std::chrono::steady_clock>; - - Log& log_; - clock_type::time_point start_ = clock_type::now(); - clock_type::time_point now_ = clock_type::now(); - clock_type::time_point report_ = clock_type::now(); - std::size_t prev_ = 0; - bool estimate_ = false; - -public: - explicit - progress(Log& log) - : log_(log) - { - } - - void - operator()(std::size_t w, std::size_t w1) - { - using namespace std::chrono; - auto const now = clock_type::now(); - if (now == now_) - return; - now_ = now; - auto const elapsed = now - start_; - if (! estimate_) - { - if (elapsed < seconds(15)) - return; - estimate_ = true; - } - else if (now - report_ < - std::chrono::seconds(60)) - { - return; - } - auto const rate = - elapsed.count() / double(w); - clock_type::duration const remain( - static_cast( - (w1 - w) * rate)); - log_ << - "Remaining: " << detail::fmtdur(remain) << - " (" << w << " of " << w1 << - " in " << detail::fmtdur(elapsed) << - ", " << (w - prev_) << - " in " << detail::fmtdur(now - report_) << - ")"; - report_ = now; - prev_ = w; - } - - void - finish() - { - log_ << - "Total time: " << detail::fmtdur( - clock_type::now() - start_); - } -}; - -//------------------------------------------------------------------------------ - -class verify_test : public unit_test::suite -{ -public: - // Runs verify on the database and reports statistics - void - do_verify (nudb::path_type const& path) - { - auto const dp = path + ".dat"; - auto const kp = path + ".key"; - print(log, test_api::verify(dp, kp)); - } - - void - run() override - { - testcase(abort_on_fail) << "verify " << arg(); - if (arg().empty()) - return fail("missing unit test argument"); - do_verify(arg()); - pass(); - } -}; - -class verify_fast_test : public unit_test::suite -{ -public: - // Runs verify on the database and reports statistics - void - do_verify (nudb::path_type const& path) - { - auto const dp = path + ".dat"; - auto const kp = path + ".key"; - progress p(log); - // VFALCO HACK 32gb hardcoded! - auto const info = verify_fast< - test_api::hash_type>( - dp, kp, 34359738368, p); - print(log, info); - } - - void - run() override - { - testcase(abort_on_fail) << "verify_fast " << arg(); - if (arg().empty()) - return fail("missing unit test argument"); - do_verify(arg()); - pass(); - } -}; - -BEAST_DEFINE_TESTSUITE_MANUAL(verify,nudb,beast); -BEAST_DEFINE_TESTSUITE_MANUAL(verify_fast,nudb,beast); - -} // test -} // nudb -} // beast diff --git a/beast/nudb/verify.h b/beast/nudb/verify.h deleted file mode 100644 index a426f90488..0000000000 --- a/beast/nudb/verify.h +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_VERIFY_H_INCLUDED -#define BEAST_NUDB_VERIFY_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { - -/** Reports database information during verify mode. */ -struct verify_info -{ - // Configured - std::size_t version = 0; // API version - std::size_t uid = 0; // UID - std::size_t appnum = 0; // Appnum - std::size_t key_size = 0; // Size of a key in bytes - std::size_t salt = 0; // Salt - std::size_t pepper = 0; // Pepper - std::size_t block_size = 0; // Block size in bytes - float load_factor = 0; // Target bucket fill fraction - - // Calculated - std::size_t capacity = 0; // Max keys per bucket - std::size_t buckets = 0; // Number of buckets - std::size_t bucket_size = 0; // Size of bucket in bytes - - // Measured - std::size_t key_file_size = 0; // Key file size in bytes - std::size_t dat_file_size = 0; // Data file size in bytes - std::size_t key_count = 0; // Keys in buckets and active spills - std::size_t value_count = 0; // Count of values in the data file - std::size_t value_bytes = 0; // Sum of value bytes in the data file - std::size_t spill_count = 0; // used number of spill records - std::size_t spill_count_tot = 0; // Number of spill records in data file - std::size_t spill_bytes = 0; // used byte of spill records - std::size_t spill_bytes_tot = 0; // Sum of spill record bytes in data file - - // Performance - float avg_fetch = 0; // average reads per fetch (excluding value) - float waste = 0; // fraction of data file bytes wasted (0..100) - float overhead = 0; // percent of extra bytes per byte of value - float actual_load = 0; // actual bucket fill fraction - - // number of buckets having n spills - std::array hist; - - verify_info() - { - hist.fill(0); - } -}; - -/** Verify consistency of the key and data files. - Effects: - Opens the key and data files in read-only mode. - Throws file_error if a file can't be opened. - Iterates the key and data files, throws store_corrupt_error - on broken invariants. -*/ -template -verify_info -verify ( - path_type const& dat_path, - path_type const& key_path, - std::size_t read_size) -{ - using namespace detail; - using File = native_file; - File df; - File kf; - if (! df.open (file_mode::scan, dat_path)) - throw store_corrupt_error( - "no data file"); - if (! kf.open (file_mode::read, key_path)) - throw store_corrupt_error( - "no key file"); - key_file_header kh; - dat_file_header dh; - read (df, dh); - read (kf, kh); - verify(dh); - verify(dh, kh); - - verify_info info; - info.version = dh.version; - info.uid = dh.uid; - info.appnum = dh.appnum; - info.key_size = dh.key_size; - info.salt = kh.salt; - info.pepper = kh.pepper; - info.block_size = kh.block_size; - info.load_factor = kh.load_factor / 65536.f; - info.capacity = kh.capacity; - info.buckets = kh.buckets; - info.bucket_size = kh.bucket_size; - info.key_file_size = kf.actual_size(); - info.dat_file_size = df.actual_size(); - - // Data Record - auto const dh_len = - field::size + // Size - kh.key_size; // Key - - std::size_t fetches = 0; - - // Iterate Data File - buffer buf (kh.block_size + dh_len); - bucket b (kh.block_size, buf.get()); - std::uint8_t* pd = buf.get() + kh.block_size; - { - bulk_reader r(df, - dat_file_header::size, - df.actual_size(), read_size); - while (! r.eof()) - { - auto const offset = r.offset(); - // Data Record or Spill Record - auto is = r.prepare( - field::size); // Size - std::size_t size; - read(is, size); - if (size > 0) - { - // Data Record - is = r.prepare( - kh.key_size + // Key - size); // Data - std::uint8_t const* const key = - is.data(kh.key_size); - std::uint8_t const* const data = - is.data(size); - (void)data; - auto const h = hash( - key, kh.key_size, kh.salt); - // Check bucket and spills - try - { - auto const n = bucket_index( - h, kh.buckets, kh.modulus); - b.read (kf, (n + 1) * kh.block_size); - ++fetches; - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "short bucket"); - } - for (;;) - { - for (auto i = b.lower_bound(h); - i < b.size(); ++i) - { - auto const item = b[i]; - if (item.hash != h) - break; - if (item.offset == offset) - goto found; - ++fetches; - } - auto const spill = b.spill(); - if (! spill) - throw store_corrupt_error( - "orphaned value"); - try - { - b.read (df, spill); - ++fetches; - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "short spill"); - } - } - found: - // Update - ++info.value_count; - info.value_bytes += size; - } - else - { - // Spill Record - is = r.prepare( - field::size); - read(is, size); // Size - if (size != kh.bucket_size) - throw store_corrupt_error( - "bad spill size"); - b.read(r); // Bucket - ++info.spill_count_tot; - info.spill_bytes_tot += - field::size + // Zero - field::size + // Size - b.compact_size(); // Bucket - } - } - } - - // Iterate Key File - { - for (std::size_t n = 0; n < kh.buckets; ++n) - { - std::size_t nspill = 0; - b.read (kf, (n + 1) * kh.block_size); - for(;;) - { - info.key_count += b.size(); - for (std::size_t i = 0; i < b.size(); ++i) - { - auto const e = b[i]; - try - { - df.read (e.offset, pd, dh_len); - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "missing value"); - } - // Data Record - istream is(pd, dh_len); - std::size_t size; - read(is, size); // Size - void const* key = - is.data(kh.key_size); // Key - if (size != e.size) - throw store_corrupt_error( - "wrong size"); - auto const h = hash(key, - kh.key_size, kh.salt); - if (h != e.hash) - throw store_corrupt_error( - "wrong hash"); - } - if (! b.spill()) - break; - try - { - b.read (df, b.spill()); - ++nspill; - ++info.spill_count; - info.spill_bytes += - field::size + // Zero - field::size + // Size - b.compact_size(); // SpillBucket - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "missing spill"); - } - } - if (nspill >= info.hist.size()) - nspill = info.hist.size() - 1; - ++info.hist[nspill]; - } - } - - float sum = 0; - for (int i = 0; i < info.hist.size(); ++i) - sum += info.hist[i] * (i + 1); - //info.avg_fetch = sum / info.buckets; - info.avg_fetch = float(fetches) / info.value_count; - info.waste = (info.spill_bytes_tot - info.spill_bytes) / - float(info.dat_file_size); - info.overhead = - float(info.key_file_size + info.dat_file_size) / - ( - info.value_bytes + - info.key_count * - (info.key_size + - // Data Record - field::size) // Size - ) - 1; - info.actual_load = info.key_count / float( - info.capacity * info.buckets); - return info; -} - -/** Verify consistency of the key and data files. - Effects: - Opens the key and data files in read-only mode. - Throws file_error if a file can't be opened. - Iterates the key and data files, throws store_corrupt_error - on broken invariants. - This uses a different algorithm that depends on allocating - a large buffer. -*/ -template -verify_info -verify_fast ( - path_type const& dat_path, - path_type const& key_path, - std::size_t buffer_size, - Progress&& progress) -{ - using namespace detail; - using File = native_file; - File df; - File kf; - if (! df.open (file_mode::scan, dat_path)) - throw store_corrupt_error( - "no data file"); - if (! kf.open (file_mode::read, key_path)) - throw store_corrupt_error( - "no key file"); - key_file_header kh; - dat_file_header dh; - read (df, dh); - read (kf, kh); - verify(dh); - verify(dh, kh); - - verify_info info; - info.version = dh.version; - info.uid = dh.uid; - info.appnum = dh.appnum; - info.key_size = dh.key_size; - info.salt = kh.salt; - info.pepper = kh.pepper; - info.block_size = kh.block_size; - info.load_factor = kh.load_factor / 65536.f; - info.capacity = kh.capacity; - info.buckets = kh.buckets; - info.bucket_size = kh.bucket_size; - info.key_file_size = kf.actual_size(); - info.dat_file_size = df.actual_size(); - - std::size_t fetches = 0; - - // Counts unverified keys per bucket - std::unique_ptr nkeys( - new std::uint32_t[kh.buckets]); - - // Verify contiguous sequential sections of the - // key file using multiple passes over the data. - // - auto const buckets = std::max(1, - buffer_size / kh.block_size); - buffer buf((buckets + 1) * kh.block_size); - bucket tmp(kh.block_size, buf.get() + - buckets * kh.block_size); - std::size_t const passes = - (kh.buckets + buckets - 1) / buckets; - auto const df_size = df.actual_size(); - std::size_t const work = passes * df_size; - std::size_t npass = 0; - for (std::size_t b0 = 0; b0 < kh.buckets; - b0 += buckets) - { - auto const b1 = std::min( - b0 + buckets, kh.buckets); - // Buffered range is [b0, b1) - auto const bn = b1 - b0; - kf.read((b0 + 1) * kh.block_size, - buf.get(), bn * kh.block_size); - // Count keys in buckets - for (std::size_t i = b0 ; i < b1; ++i) - { - bucket b(kh.block_size, buf.get() + - (i - b0) * kh.block_size); - nkeys[i] = b.size(); - std::size_t nspill = 0; - auto spill = b.spill(); - while (spill != 0) - { - tmp.read(df, spill); - nkeys[i] += tmp.size(); - spill = tmp.spill(); - ++nspill; - ++info.spill_count; - info.spill_bytes += - field::size + // Zero - field::size + // Size - tmp.compact_size(); // SpillBucket - } - if (nspill >= info.hist.size()) - nspill = info.hist.size() - 1; - ++info.hist[nspill]; - info.key_count += nkeys[i]; - } - // Iterate Data File - bulk_reader r(df, - dat_file_header::size, df_size, - 64 * 1024 * 1024); - while (! r.eof()) - { - auto const offset = r.offset(); - progress(npass * df_size + offset, work); - // Data Record or Spill Record - auto is = r.prepare( - field::size); // Size - std::size_t size; - read(is, size); - if (size > 0) - { - // Data Record - is = r.prepare( - kh.key_size + // Key - size); // Data - std::uint8_t const* const key = - is.data(kh.key_size); - std::uint8_t const* const data = - is.data(size); - (void)data; - auto const h = hash( - key, kh.key_size, kh.salt); - auto const n = bucket_index( - h, kh.buckets, kh.modulus); - if (n < b0 || n >= b1) - continue; - // Check bucket and spills - bucket b (kh.block_size, buf.get() + - (n - b0) * kh.block_size); - ++fetches; - for (;;) - { - for (auto i = b.lower_bound(h); - i < b.size(); ++i) - { - auto const item = b[i]; - if (item.hash != h) - break; - if (item.offset == offset) - goto found; - ++fetches; - } - auto const spill = b.spill(); - if (! spill) - throw store_corrupt_error( - "orphaned value"); - b = tmp; - try - { - b.read (df, spill); - ++fetches; - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "short spill"); - } - } - found: - // Update - ++info.value_count; - info.value_bytes += size; - if (nkeys[n]-- == 0) - throw store_corrupt_error( - "duplicate value"); - } - else - { - // Spill Record - is = r.prepare( - field::size); - read(is, size); // Size - if (size != kh.bucket_size) - throw store_corrupt_error( - "bad spill size"); - tmp.read(r); // Bucket - if (b0 == 0) - { - ++info.spill_count_tot; - info.spill_bytes_tot += - field::size + // Zero - field::size + // Size - tmp.compact_size(); // Bucket - } - } - } - ++npass; - } - - // Make sure every key in every bucket was visited - for (std::size_t i = 0; - i < kh.buckets; ++i) - if (nkeys[i] != 0) - throw store_corrupt_error( - "orphan value"); - - float sum = 0; - for (int i = 0; i < info.hist.size(); ++i) - sum += info.hist[i] * (i + 1); - //info.avg_fetch = sum / info.buckets; - info.avg_fetch = float(fetches) / info.value_count; - info.waste = (info.spill_bytes_tot - info.spill_bytes) / - float(info.dat_file_size); - info.overhead = - float(info.key_file_size + info.dat_file_size) / - ( - info.value_bytes + - info.key_count * - (info.key_size + - // Data Record - field::size) // Size - ) - 1; - info.actual_load = info.key_count / float( - info.capacity * info.buckets); - return info; -} - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/visit.h b/beast/nudb/visit.h deleted file mode 100644 index 9243101f66..0000000000 --- a/beast/nudb/visit.h +++ /dev/null @@ -1,111 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_VISIT_H_INCLUDED -#define BEAST_NUDB_VISIT_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace nudb { - -/** Visit each key/data pair in a database file. - - Function will be called with this signature: - bool(void const* key, std::size_t key_size, - void const* data, std::size_t size) - - If Function returns false, the visit is terminated. - - @return `true` if the visit completed - This only requires the data file. -*/ -template -bool -visit( - path_type const& path, - std::size_t read_size, - Function&& f) -{ - using namespace detail; - using File = native_file; - File df; - df.open (file_mode::scan, path); - dat_file_header dh; - read (df, dh); - verify (dh); - Codec codec; - // Iterate Data File - bulk_reader r( - df, dat_file_header::size, - df.actual_size(), read_size); - buffer buf; - try - { - while (! r.eof()) - { - // Data Record or Spill Record - std::size_t size; - auto is = r.prepare( - field::size); // Size - read(is, size); - if (size > 0) - { - // Data Record - is = r.prepare( - dh.key_size + // Key - size); // Data - std::uint8_t const* const key = - is.data(dh.key_size); - auto const result = codec.decompress( - is.data(size), size, buf); - if (! f(key, dh.key_size, - result.first, result.second)) - return false; - } - else - { - // Spill Record - is = r.prepare( - field::size); - read(is, size); // Size - r.prepare(size); // skip bucket - } - } - } - catch (file_short_read_error const&) - { - throw store_corrupt_error( - "nudb: data short read"); - } - - return true; -} - -} // nudb -} // beast - -#endif diff --git a/beast/nudb/win32_file.h b/beast/nudb/win32_file.h deleted file mode 100644 index 3d00850ca0..0000000000 --- a/beast/nudb/win32_file.h +++ /dev/null @@ -1,462 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_NUDB_DETAIL_WIN32_FILE_H_INCLUDED -#define BEAST_NUDB_DETAIL_WIN32_FILE_H_INCLUDED - -#include -#include -#include - -#ifndef BEAST_NUDB_WIN32_FILE -# ifdef _MSC_VER -# define BEAST_NUDB_WIN32_FILE 1 -# else -# define BEAST_NUDB_WIN32_FILE 0 -# endif -#endif - -#if BEAST_NUDB_WIN32_FILE -#pragma push_macro("NOMINMAX") -#pragma push_macro("UNICODE") -#pragma push_macro("STRICT") -# ifndef NOMINMAX -# define NOMINMAX -# endif -# ifndef UNICODE -# define UNICODE -# endif -# ifndef STRICT -# define STRICT -# endif -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include -#pragma pop_macro("STRICT") -#pragma pop_macro("UNICODE") -#pragma pop_macro("NOMINMAX") -#endif - -namespace beast { -namespace nudb { - -#if BEAST_NUDB_WIN32_FILE - -namespace detail { - -// Win32 error code -class file_win32_error - : public file_error -{ -public: - explicit - file_win32_error (char const* m, - DWORD dwError = ::GetLastError()) - : file_error (std::string("nudb: ") + m + - ", " + text(dwError)) - { - } - - explicit - file_win32_error (std::string const& m, - DWORD dwError = ::GetLastError()) - : file_error (std::string("nudb: ") + m + - ", " + text(dwError)) - { - } - -private: - template - static - std::string - text (DWORD dwError); -}; - -template -std::string -file_win32_error::text (DWORD dwError) -{ - LPSTR buf = nullptr; - size_t const size = FormatMessageA ( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - dwError, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&buf, - 0, - NULL); - std::string s; - if (size) - { - s.append(buf, size); - LocalFree (buf); - } - else - { - s = "error " + std::to_string(dwError); - } - return s; -} - -//------------------------------------------------------------------------------ - -template -class win32_file -{ -private: - HANDLE hf_ = INVALID_HANDLE_VALUE; - -public: - win32_file() = default; - win32_file (win32_file const&) = delete; - win32_file& operator= (win32_file const&) = delete; - - ~win32_file(); - - win32_file (win32_file&&); - - win32_file& - operator= (win32_file&& other); - - bool - is_open() const - { - return hf_ != INVALID_HANDLE_VALUE; - } - - void - close(); - - // Returns: - // `false` if the file already exists - // `true` on success, else throws - // - bool - create (file_mode mode, std::string const& path); - - // Returns: - // `false` if the file doesnt exist - // `true` on success, else throws - // - bool - open (file_mode mode, std::string const& path); - - // Effects: - // Removes the file from the file system. - // - // Throws: - // Throws is an error occurs. - // - // Returns: - // `true` if the file was erased - // `false` if the file was not present - // - static - bool - erase (path_type const& path); - - // Returns: - // Current file size in bytes measured by operating system - // Requires: - // is_open() == true - // - std::size_t - actual_size() const; - - void - read (std::size_t offset, - void* buffer, std::size_t bytes); - - void - write (std::size_t offset, - void const* buffer, std::size_t bytes); - - void - sync(); - - void - trunc (std::size_t length); - -private: - static - std::pair - flags (file_mode mode); -}; - -template -win32_file<_>::~win32_file() -{ - close(); -} - -template -win32_file<_>::win32_file (win32_file&& other) - : hf_ (other.hf_) -{ - other.hf_ = INVALID_HANDLE_VALUE; -} - -template -win32_file<_>& -win32_file<_>::operator= (win32_file&& other) -{ - if (&other == this) - return *this; - close(); - hf_ = other.hf_; - other.hf_ = INVALID_HANDLE_VALUE; - return *this; -} - -template -void -win32_file<_>::close() -{ - if (hf_ != INVALID_HANDLE_VALUE) - { - ::CloseHandle(hf_); - hf_ = INVALID_HANDLE_VALUE; - } -} - -template -bool -win32_file<_>::create (file_mode mode, - std::string const& path) -{ - assert(! is_open()); - auto const f = flags(mode); - hf_ = ::CreateFileA (path.c_str(), - f.first, - 0, - NULL, - CREATE_NEW, - f.second, - NULL); - if (hf_ == INVALID_HANDLE_VALUE) - { - DWORD const dwError = ::GetLastError(); - if (dwError != ERROR_FILE_EXISTS) - throw file_win32_error( - "create file", dwError); - return false; - } - return true; -} - -template -bool -win32_file<_>::open (file_mode mode, - std::string const& path) -{ - assert(! is_open()); - auto const f = flags(mode); - hf_ = ::CreateFileA (path.c_str(), - f.first, - 0, - NULL, - OPEN_EXISTING, - f.second, - NULL); - if (hf_ == INVALID_HANDLE_VALUE) - { - DWORD const dwError = ::GetLastError(); - if (dwError != ERROR_FILE_NOT_FOUND && - dwError != ERROR_PATH_NOT_FOUND) - throw file_win32_error( - "open file", dwError); - return false; - } - return true; -} - -template -bool -win32_file<_>::erase (path_type const& path) -{ - BOOL const bSuccess = - ::DeleteFileA(path.c_str()); - if (! bSuccess) - { - DWORD dwError = ::GetLastError(); - if (dwError != ERROR_FILE_NOT_FOUND && - dwError != ERROR_PATH_NOT_FOUND) - throw file_win32_error( - "erase file"); - return false; - } - return true; -} - -// Return: Current file size in bytes measured by operating system -template -std::size_t -win32_file<_>::actual_size() const -{ - assert(is_open()); - LARGE_INTEGER fileSize; - if (! ::GetFileSizeEx(hf_, &fileSize)) - throw file_win32_error( - "size file"); - return static_cast(fileSize.QuadPart); -} - -template -void -win32_file<_>::read (std::size_t offset, - void* buffer, std::size_t bytes) -{ - while(bytes > 0) - { - DWORD bytesRead; - LARGE_INTEGER li; - li.QuadPart = static_cast(offset); - OVERLAPPED ov; - ov.Offset = li.LowPart; - ov.OffsetHigh = li.HighPart; - ov.hEvent = NULL; - BOOL const bSuccess = ::ReadFile( - hf_, buffer, bytes, &bytesRead, &ov); - if (! bSuccess) - { - DWORD const dwError = ::GetLastError(); - if (dwError != ERROR_HANDLE_EOF) - throw file_win32_error( - "read file", dwError); - throw file_short_read_error(); - } - if (bytesRead == 0) - throw file_short_read_error(); - offset += bytesRead; - bytes -= bytesRead; - buffer = reinterpret_cast( - buffer) + bytesRead; - } -} - -template -void -win32_file<_>::write (std::size_t offset, - void const* buffer, std::size_t bytes) -{ - while(bytes > 0) - { - LARGE_INTEGER li; - li.QuadPart = static_cast(offset); - OVERLAPPED ov; - ov.Offset = li.LowPart; - ov.OffsetHigh = li.HighPart; - ov.hEvent = NULL; - DWORD bytesWritten; - BOOL const bSuccess = ::WriteFile( - hf_, buffer, bytes, &bytesWritten, &ov); - if (! bSuccess) - throw file_win32_error( - "write file"); - if (bytesWritten == 0) - throw file_short_write_error(); - offset += bytesWritten; - bytes -= bytesWritten; - buffer = reinterpret_cast< - char const*>(buffer) + - bytesWritten; - } -} - -template -void -win32_file<_>::sync() -{ - BOOL const bSuccess = - ::FlushFileBuffers(hf_); - if (! bSuccess) - throw file_win32_error( - "sync file"); -} - -template -void -win32_file<_>::trunc (std::size_t length) -{ - LARGE_INTEGER li; - li.QuadPart = length; - BOOL bSuccess; - bSuccess = ::SetFilePointerEx( - hf_, li, NULL, FILE_BEGIN); - if (bSuccess) - bSuccess = SetEndOfFile(hf_); - if (! bSuccess) - throw file_win32_error( - "trunc file"); -} - -template -std::pair -win32_file<_>::flags (file_mode mode) -{ - std::pair result(0, 0); - switch (mode) - { - case file_mode::scan: - result.first = - GENERIC_READ; - result.second = - FILE_FLAG_SEQUENTIAL_SCAN; - break; - - case file_mode::read: - result.first = - GENERIC_READ; - result.second = - FILE_FLAG_RANDOM_ACCESS; - break; - - case file_mode::append: - result.first = - GENERIC_READ | GENERIC_WRITE; - result.second = - FILE_FLAG_RANDOM_ACCESS - //| FILE_FLAG_NO_BUFFERING - //| FILE_FLAG_WRITE_THROUGH - ; - break; - - case file_mode::write: - result.first = - GENERIC_READ | GENERIC_WRITE; - result.second = - FILE_FLAG_RANDOM_ACCESS; - break; - } - return result; -} - -} // detail - -using win32_file = detail::win32_file<>; - -#endif - -} // nudb -} // detail - -#endif diff --git a/beast/rngfill.h b/beast/rngfill.h deleted file mode 100644 index d2bd7b5fda..0000000000 --- a/beast/rngfill.h +++ /dev/null @@ -1,69 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_RANDOM_RNGFILL_H_INCLUDED -#define BEAST_RANDOM_RNGFILL_H_INCLUDED - -#include -#include -#include -#include - -namespace beast { - -template -void -rngfill (void* buffer, std::size_t bytes, - Generator& g) -{ - using result_type = - typename Generator::result_type; - while (bytes >= sizeof(result_type)) - { - auto const v = g(); - std::memcpy(buffer, &v, sizeof(v)); - buffer = reinterpret_cast< - std::uint8_t*>(buffer) + sizeof(v); - bytes -= sizeof(v); - } - if (bytes > 0) - { - auto const v = g(); - std::memcpy(buffer, &v, bytes); - } -} - -template > -void -rngfill (std::array& a, Generator& g) -{ - using result_type = - typename Generator::result_type; - auto i = N / sizeof(result_type); - result_type* p = - reinterpret_cast(a.data()); - while (i--) - *p++ = g(); -} - -} // beast - -#endif diff --git a/beast/smart_ptr/SharedObject.h b/beast/smart_ptr/SharedObject.h deleted file mode 100644 index fc57bb1500..0000000000 --- a/beast/smart_ptr/SharedObject.h +++ /dev/null @@ -1,134 +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_SMART_PTR_SHAREDOBJECT_H_INCLUDED -#define BEAST_SMART_PTR_SHAREDOBJECT_H_INCLUDED - -#include -#include - -#include - -namespace beast { - -//============================================================================== -/** - Adds reference-counting to an object. - - To add reference-counting to a class, derive it from this class, and - use the SharedPtr class to point to it. - - e.g. @code - class MyClass : public SharedObject - { - void foo(); - - // This is a neat way of declaring a using Ptr = for a pointer class, - // rather than typing out the full templated name each time.. - using Ptr = SharedPtr; - }; - - MyClass::Ptr p = new MyClass(); - MyClass::Ptr p2 = p; - p = nullptr; - p2->foo(); - @endcode - - Once a new SharedObject has been assigned to a pointer, be - careful not to delete the object manually. - - This class uses an std::atomic value to hold the reference count, so - that the pointers can be passed between threads safely. - - @see SharedPtr, SharedObjectArray -*/ -class SharedObject -{ -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. - */ - void incReferenceCount() const noexcept - { - ++refCount; - } - - /** Decreases the object's reference count. */ - void decReferenceCount () const - { - assert (getReferenceCount() > 0); - if (--refCount == 0) - destroy (); - } - - /** Returns the object's current reference count. */ - int getReferenceCount() const noexcept - { - return refCount.load(); - } - -protected: - //============================================================================== - /** Creates the reference-counted object (with an initial ref count of zero). */ - SharedObject() - : refCount (0) - { - } - - SharedObject (SharedObject const&) = delete; - SharedObject& operator= (SharedObject const&) = delete; - - /** Destructor. */ - virtual ~SharedObject() - { - // it's dangerous to delete an object that's still referenced by something else! - assert (getReferenceCount() == 0); - } - - /** Destroy the object. - Derived classes can override this for different behaviors. - */ - virtual void destroy () const - { - delete this; - } - - /** Resets the reference count to zero without deleting the object. - You should probably never need to use this! - */ - void resetReferenceCount() noexcept - { - refCount.store (0); - } - -private: - //============================================================================== - std::atomic mutable refCount; -}; - -} - -#endif diff --git a/beast/smart_ptr/SharedPtr.h b/beast/smart_ptr/SharedPtr.h deleted file mode 100644 index 1f5f31a894..0000000000 --- a/beast/smart_ptr/SharedPtr.h +++ /dev/null @@ -1,327 +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_SMART_PTR_SHAREDPTR_H_INCLUDED -#define BEAST_SMART_PTR_SHAREDPTR_H_INCLUDED - -#include -#include - -namespace beast { - -// Visual Studio doesn't seem to do very well when it comes -// to templated constructors and assignments so we provide -// non-templated versions when U and T are the same type. -// -#ifndef BEAST_SHAREDPTR_PROVIDE_COMPILER_WORKAROUNDS -#define BEAST_SHAREDPTR_PROVIDE_COMPILER_WORKAROUNDS 1 -#endif - -/** A smart-pointer container. - - Requirement: - T must support the SharedObject concept. - - The template parameter specifies the class of the object you want to point - to - the easiest way to make a class reference-countable is to simply make - it inherit from SharedObject, but if you need to, you could roll your own - reference-countable class by implementing a pair of methods called - incReferenceCount() and decReferenceCount(). - - When using this class, you'll probably want to create a using MyClassPtr = to - abbreviate the full templated name - e.g. - - @code - - using MyClassPtr = SharedPtr ; - - @endcode - - @see SharedObject, SharedObjectArray -*/ -template -class SharedPtr -{ -public: - using value_type = T; - - /** The class being referenced by this container. */ - using ReferencedType = T; - - /** Construct a container pointing to nothing. */ - SharedPtr () noexcept - : m_p (nullptr) - { - } - - /** Construct a container holding an object. - This will increment the object's reference-count if it is non-null. - Requirement: - U* must be convertible to T* - */ - /** @{ */ - SharedPtr (T* t) noexcept - : m_p (acquire (t)) - { - } - - template - SharedPtr (U* u) noexcept - : m_p (acquire (u)) - { - } - /** @} */ - - /** Construct a container holding an object from another container. - This will increment the object's reference-count (if it is non-null). - Requirement: - U* must be convertible to T* - */ - /** @{ */ -#if BEAST_SHAREDPTR_PROVIDE_COMPILER_WORKAROUNDS - SharedPtr (SharedPtr const& sp) noexcept - : m_p (acquire (sp.get ())) - { - } -#endif - - template - SharedPtr (SharedPtr const& sp) noexcept - : m_p (acquire (sp.get ())) - { - } - /** @} */ - - /** Assign a different object to the container. - The previous object beind held, if any, loses a reference count and - will be destroyed if it is the last reference. - Requirement: - U* must be convertible to T* - */ - /** @{ */ -#if BEAST_SHAREDPTR_PROVIDE_COMPILER_WORKAROUNDS - SharedPtr& operator= (T* t) - { - return assign (t); - } -#endif - - template - SharedPtr& operator= (U* u) - { - return assign (u); - } - /** @} */ - - /** Assign an object from another container to this one. */ - /** @{ */ - SharedPtr& operator= (SharedPtr const& sp) - { - return assign (sp.get ()); - } - - /** Assign an object from another container to this one. */ - template - SharedPtr& operator= (SharedPtr const& sp) - { - return assign (sp.get ()); - } - /** @} */ - -#if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS - /** Construct a container with an object transferred from another container. - The originating container loses its reference to the object. - Requires: - U* must be convertible to T* - */ - /** @{ */ -#if BEAST_SHAREDPTR_PROVIDE_COMPILER_WORKAROUNDS - SharedPtr (SharedPtr && sp) noexcept - : m_p (sp.swap (nullptr)) - { - } -#endif - - template - SharedPtr (SharedPtr && sp) noexcept - : m_p (sp.template swap (nullptr)) - { - } - /** @} */ - - /** Transfer ownership of another object to this container. - The originating container loses its reference to the object. - Requires: - U* must be convertible to T* - */ - /** @{ */ -#if BEAST_SHAREDPTR_PROVIDE_COMPILER_WORKAROUNDS - SharedPtr& operator= (SharedPtr && sp) - { - return assign (sp.swap (nullptr)); - } -#endif - - template - SharedPtr& operator= (SharedPtr && sp) - { - return assign (sp.template swap (nullptr)); - } - /** @} */ -#endif - - /** Destroy the container and release the held reference, if any. - */ - ~SharedPtr () - { - release (m_p); - } - - /** Returns `true` if the container is not pointing to an object. */ - bool empty () const noexcept - { - return m_p == nullptr; - } - - /** Returns the object that this pointer references if any, else nullptr. */ - operator T* () const noexcept - { - return m_p; - } - - /** Returns the object that this pointer references if any, else nullptr. */ - T* operator-> () const noexcept - { - return m_p; - } - - /** Returns the object that this pointer references if any, else nullptr. */ - T* get () const noexcept - { - return m_p; - } - -private: - // Acquire a reference to u for the caller. - // - template - static T* acquire (U* u) noexcept - { - if (u != nullptr) - u->incReferenceCount (); - return u; - } - - static void release (T* t) - { - if (t != nullptr) - t->decReferenceCount (); - } - - // Swap ownership of the currently referenced object. - // The caller receives a pointer to the original object, - // and this container is left with the passed object. No - // reference counts are changed. - // - template - T* swap (U* u) - { - T* const t (m_p); - m_p = u; - return t; - } - - // Acquire ownership of u. - // Any previous reference is released. - // - template - SharedPtr& assign (U* u) - { - if (m_p != u) - release (this->swap (acquire (u))); - return *this; - } - - T* m_p; -}; - -//------------------------------------------------------------------------------ - -// bind() helpers for pointer to member function - -template -const T* get_pointer (SharedPtr const& ptr) -{ - return ptr.get(); -} - -template -T* get_pointer (SharedPtr& ptr) -{ - return ptr.get(); -} - -//------------------------------------------------------------------------------ - -/** SharedPtr comparisons. */ -/** @{ */ -template -bool operator== (SharedPtr const& lhs, U* const rhs) noexcept -{ - return lhs.get() == rhs; -} - -template -bool operator== (SharedPtr const& lhs, SharedPtr const& rhs) noexcept -{ - return lhs.get() == rhs.get(); -} - -template -bool operator== (T const* lhs, SharedPtr const& rhs) noexcept -{ - return lhs == rhs.get(); -} - -template -bool operator!= (SharedPtr const& lhs, U const* rhs) noexcept -{ - return lhs.get() != rhs; -} - -template -bool operator!= (SharedPtr const& lhs, SharedPtr const& rhs) noexcept -{ - return lhs.get() != rhs.get(); -} - -template -bool operator!= (T const* lhs, SharedPtr const& rhs) noexcept -{ - return lhs != rhs.get(); -} -/** @} */ - -} - -#endif diff --git a/beast/streams/streams.unity.cpp b/beast/streams/streams.unity.cpp deleted file mode 100644 index f997894530..0000000000 --- a/beast/streams/streams.unity.cpp +++ /dev/null @@ -1,20 +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 diff --git a/beast/streams/tests/basic_abstract_ostream.test.cpp b/beast/streams/tests/beast_basic_abstract_ostream_test.cpp similarity index 100% rename from beast/streams/tests/basic_abstract_ostream.test.cpp rename to beast/streams/tests/beast_basic_abstract_ostream_test.cpp diff --git a/beast/utility/tests/empty_base_optimization.test.cpp b/beast/test/beast_empty_base_optimization_test.cpp similarity index 98% rename from beast/utility/tests/empty_base_optimization.test.cpp rename to beast/test/beast_empty_base_optimization_test.cpp index a4448a5831..c21ca370da 100644 --- a/beast/utility/tests/empty_base_optimization.test.cpp +++ b/beast/test/beast_empty_base_optimization_test.cpp @@ -21,7 +21,7 @@ #include #endif -#include +#include #include diff --git a/beast/threads/Stoppable.h b/beast/threads/Stoppable.h deleted file mode 100644 index 25ac9959d2..0000000000 --- a/beast/threads/Stoppable.h +++ /dev/null @@ -1,378 +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_THREADS_STOPPABLE_H_INCLUDED -#define BEAST_THREADS_STOPPABLE_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -namespace beast { - -class RootStoppable; - -/** Provides an interface for starting and stopping. - - A common method of structuring server or peer to peer code is to isolate - conceptual portions of functionality into individual classes, aggregated - into some larger "application" or "core" object which holds all the parts. - Frequently, these components are dependent on each other in unavoidably - complex ways. They also often use threads and perform asynchronous i/o - operations involving sockets or other operating system objects. The process - of starting and stopping such a system can be complex. This interface - provides a set of behaviors for ensuring that the start and stop of a - composite application-style object is well defined. - - Upon the initialization of the composite object these steps are peformed: - - 1. Construct sub-components. - - These are all typically derived from Stoppable. There can be a deep - hierarchy: Stoppable objects may themselves have Stoppable child - objects. This captures the relationship of dependencies. - - 2. prepare() - - Because some components may depend on others, preparatory steps require - that all objects be first constructed. The prepare step calls all - Stoppable objects in the tree starting from the leaves and working up - to the root. In this stage we are guaranteed that all objects have been - constructed and are in a well-defined state. - - 3. onPrepare() - - This override is called for all Stoppable objects in the hierarchy - during the prepare stage. It is guaranteed that all child Stoppable - objects have already been prepared when this is called. - - Objects are called children first. - - 4. start() - - At this point all sub-components have been constructed and prepared, - so it should be safe for them to be started. While some Stoppable - objects may do nothing in their start function, others will start - threads or call asynchronous i/o initiating functions like timers or - sockets. - - 5. onStart() - - This override is called for all Stoppable objects in the hierarchy - during the start stage. It is guaranteed that no child Stoppable - objects have been started when this is called. - - Objects are called parent first. - - This is the sequence of events involved in stopping: - - 6. stopAsync() [optional] - - This notifies the root Stoppable and all its children that a stop is - requested. - - 7. stop() - - This first calls stopAsync(), and then blocks on each child Stoppable in - the in the tree from the bottom up, until the Stoppable indicates it has - stopped. This will usually be called from the main thread of execution - when some external signal indicates that the process should stop. For - example, an RPC 'stop' command, or a SIGINT POSIX signal. - - 8. onStop() - - This override is called for the root Stoppable and all its children when - stopAsync() is called. Derived classes should cancel pending I/O and - timers, signal that threads should exit, queue cleanup jobs, and perform - any other necessary final actions in preparation for exit. - - Objects are called parent first. - - 9. onChildrenStopped() - - This override is called when all the children have stopped. This informs - the Stoppable that there should not be any more dependents making calls - into its member functions. A Stoppable that has no children will still - have this function called. - - Objects are called children first. - - 10. stopped() - - The derived class calls this function to inform the Stoppable API that - it has completed the stop. This unblocks the caller of stop(). - - For stoppables which are only considered stopped when all of their - children have stopped, and their own internal logic indicates a stop, it - will be necessary to perform special actions in onChildrenStopped(). The - funtion areChildrenStopped() can be used after children have stopped, - but before the Stoppable logic itself has stopped, to determine if the - stoppable's logic is a true stop. - - Pseudo code for this process is as follows: - - @code - - // Returns `true` if derived logic has stopped. - // - // When the logic stops, logicProcessingStop() is no longer called. - // If children are still active we need to wait until we get a - // notification that the children have stopped. - // - bool logicHasStopped (); - - // Called when children have stopped - void onChildrenStopped () - { - // We have stopped when the derived logic stops and children stop. - if (logicHasStopped) - stopped(); - } - - // derived-specific logic that executes periodically - void logicProcessingStep () - { - // process - // ... - - // now see if we've stopped - if (logicHasStopped() && areChildrenStopped()) - stopped(); - } - - @endcode - - Derived class that manage one or more threads should typically notify - those threads in onStop that they should exit. In the thread function, - when the last thread is about to exit it would call stopped(). - - @note A Stoppable may not be restarted. -*/ -/** @{ */ -class Stoppable -{ -protected: - Stoppable (char const* name, RootStoppable& root); - -public: - /** Create the Stoppable. */ - Stoppable (char const* name, Stoppable& parent); - - /** Destroy the Stoppable. */ - virtual ~Stoppable (); - - /** Returns `true` if the stoppable should stop. */ - bool isStopping () const; - - /** Returns `true` if the requested stop has completed. */ - bool isStopped () const; - - /** Returns `true` if all children have stopped. */ - bool areChildrenStopped () const; - - /** Sleep or wake up on stop. - - @return `true` if we are stopping - */ - template - bool - alertable_sleep_for( - std::chrono::duration const& d); - -protected: - /** Called by derived classes to indicate that the stoppable has stopped. */ - void stopped (); - -private: - /** Override called during preparation. - Since all other Stoppable objects in the tree have already been - constructed, this provides an opportunity to perform initialization which - depends on calling into other Stoppable objects. - This call is made on the same thread that called prepare(). - The default implementation does nothing. - Guaranteed to only be called once. - */ - virtual void onPrepare (); - - /** Override called during start. */ - virtual void onStart (); - - /** Override called when the stop notification is issued. - - The call is made on an unspecified, implementation-specific thread. - onStop and onChildrenStopped will never be called concurrently, across - all Stoppable objects descended from the same root, inclusive of the - root. - - It is safe to call isStopping, isStopped, and areChildrenStopped from - within this function; The values returned will always be valid and never - change during the callback. - - The default implementation simply calls stopped(). This is applicable - when the Stoppable has a trivial stop operation (or no stop operation), - and we are merely using the Stoppable API to position it as a dependency - of some parent service. - - Thread safety: - May not block for long periods. - Guaranteed only to be called once. - Must be safe to call from any thread at any time. - */ - virtual void onStop (); - - /** Override called when all children have stopped. - - The call is made on an unspecified, implementation-specific thread. - onStop and onChildrenStopped will never be called concurrently, across - all Stoppable objects descended from the same root, inclusive of the - root. - - It is safe to call isStopping, isStopped, and areChildrenStopped from - within this function; The values returned will always be valid and never - change during the callback. - - The default implementation does nothing. - - Thread safety: - May not block for long periods. - Guaranteed only to be called once. - Must be safe to call from any thread at any time. - */ - virtual void onChildrenStopped (); - - friend class RootStoppable; - - struct Child; - using Children = LockFreeStack ; - - struct Child : Children::Node - { - Child (Stoppable* stoppable_) : stoppable (stoppable_) - { - } - - Stoppable* stoppable; - }; - - void prepareRecursive (); - void startRecursive (); - void stopAsyncRecursive (Journal j); - void stopRecursive (Journal j); - - std::string m_name; - RootStoppable& m_root; - Child m_child; - std::atomic m_started; - std::atomic m_stopped; - std::atomic m_childrenStopped; - Children m_children; - WaitableEvent m_stoppedEvent; -}; - -//------------------------------------------------------------------------------ - -class RootStoppable : public Stoppable -{ -public: - explicit RootStoppable (char const* name); - - ~RootStoppable () = default; - - bool isStopping() const; - - /** Prepare all contained Stoppable objects. - This calls onPrepare for all Stoppable objects in the tree. - Calls made after the first have no effect. - Thread safety: - May be called from any thread. - */ - void prepare (); - - /** Start all contained Stoppable objects. - The default implementation does nothing. - Calls made after the first have no effect. - Thread safety: - May be called from any thread. - */ - void start (); - - /** Notify a root stoppable and children to stop, and block until stopped. - Has no effect if the stoppable was already notified. - This blocks until the stoppable and all of its children have stopped. - Undefined behavior results if stop() is called without a previous call - to start(). - Thread safety: - Safe to call from any thread not associated with a Stoppable. - */ - void stop (Journal j); - - /** Sleep or wake up on stop. - - @return `true` if we are stopping - */ - template - bool - alertable_sleep_for( - std::chrono::duration const& d); - -private: - /* Notify a root stoppable and children to stop, without waiting. - Has no effect if the stoppable was already notified. - - Thread safety: - Safe to call from any thread at any time. - */ - void stopAsync(Journal j); - - std::atomic m_prepared; - bool m_calledStop; - std::atomic m_calledStopAsync; - std::mutex m_; - std::condition_variable c_; -}; -/** @} */ - -//------------------------------------------------------------------------------ - -template -bool -RootStoppable::alertable_sleep_for( - std::chrono::duration const& d) -{ - std::unique_lock lock(m_); - if (m_calledStop) - return true; - return c_.wait_for(lock, d, [this]{return m_calledStop;}); -} - -template -bool -Stoppable::alertable_sleep_for( - std::chrono::duration const& d) -{ - return m_root.alertable_sleep_for(d); -} - -} - -#endif diff --git a/beast/threads/Thread.h b/beast/threads/Thread.h deleted file mode 100644 index 391dbfd321..0000000000 --- a/beast/threads/Thread.h +++ /dev/null @@ -1,187 +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_THREADS_THREAD_H_INCLUDED -#define BEAST_THREADS_THREAD_H_INCLUDED - -#include - -#include -#include - -namespace beast { - -//============================================================================== -/** - Encapsulates a thread. - - Subclasses derive from Thread and implement the run() method, in which they - do their business. The thread can then be started with the startThread() method - and controlled with various other methods. - - @see WaitableEvent, Process, ThreadWithProgressWindow, - MessageManagerLock -*/ -class Thread -{ -public: - //============================================================================== - /** - Creates a thread. - - When first created, the thread is not running. Use the startThread() - method to start it. - */ - explicit Thread (std::string const& threadName); - - Thread (Thread const&) = delete; - Thread& operator= (Thread const&) = delete; - - /** Destructor. - - If the thread has not been stopped first, this will generate a fatal error. - */ - virtual ~Thread(); - - //============================================================================== - /** Must be implemented to perform the thread's actual code. - - Remember that the thread must regularly check the threadShouldExit() - method whilst running, and if this returns true it should return from - the run() method as soon as possible to avoid being forcibly killed. - - @see threadShouldExit, startThread - */ - virtual void run() = 0; - - //============================================================================== - // Thread control functions.. - - /** Starts the thread running. - - This will start the thread's run() method. - (if it's already started, startThread() won't do anything). - - @see stopThread - */ - void startThread(); - - /** Attempts to stop the thread running. - - This method will cause the threadShouldExit() method to return true - and call notify() in case the thread is currently waiting. - */ - void stopThread (); - - /** Stop the thread without blocking. - This calls signalThreadShouldExit followed by notify. - */ - void stopThreadAsync (); - - //============================================================================== - /** Returns true if the thread is currently active */ - bool isThreadRunning() const; - - /** Sets a flag to tell the thread it should stop. - - Calling this means that the threadShouldExit() method will then return true. - The thread should be regularly checking this to see whether it should exit. - - If your thread makes use of wait(), you might want to call notify() after calling - this method, to interrupt any waits that might be in progress, and allow it - to reach a point where it can exit. - - @see threadShouldExit - @see waitForThreadToExit - */ - void signalThreadShouldExit(); - - /** Checks whether the thread has been told to stop running. - - Threads need to check this regularly, and if it returns true, they should - return from their run() method at the first possible opportunity. - - @see signalThreadShouldExit - */ - inline bool threadShouldExit() const { return shouldExit; } - - /** Waits for the thread to stop. - - This will waits until isThreadRunning() is false. - */ - void waitForThreadToExit () const; - - //============================================================================== - /** Makes the thread wait for a notification. - - This puts the thread to sleep until either the timeout period expires, or - another thread calls the notify() method to wake it up. - - 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) const; - - /** Wakes up the thread. - - If the thread has called the wait() method, this will wake it up. - - @see wait - */ - void notify() const; - - //============================================================================== - /** Returns the name of the thread. - - This is the name that gets set in the constructor. - */ - std::string const& getThreadName() const { return threadName; } - - /** Changes the name of the caller thread. - Different OSes may place different length or content limits on this name. - */ - static void setCurrentThreadName (std::string const& newThreadName); - - -private: - //============================================================================== - std::string const threadName; - void* volatile threadHandle; - std::recursive_mutex startStopLock; - WaitableEvent startSuspensionEvent, defaultEvent; - bool volatile shouldExit; - - #ifndef DOXYGEN - friend void beast_threadEntryPoint (void*); - #endif - - void launchThread(); - void closeThreadHandle(); - void threadEntryPoint(); -}; - -} - -#endif - diff --git a/beast/threads/Threads.unity.cpp b/beast/threads/Threads.unity.cpp deleted file mode 100644 index dd0de1b53d..0000000000 --- a/beast/threads/Threads.unity.cpp +++ /dev/null @@ -1,27 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include -#include -#include -#include diff --git a/beast/threads/WaitableEvent.h b/beast/threads/WaitableEvent.h deleted file mode 100644 index 3eeb827903..0000000000 --- a/beast/threads/WaitableEvent.h +++ /dev/null @@ -1,124 +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_THREADS_WAITABLEEVENT_H_INCLUDED -#define BEAST_THREADS_WAITABLEEVENT_H_INCLUDED - -#include - -#if ! BEAST_WINDOWS -#include -#endif - -namespace beast { - -/** Allows threads to wait for events triggered by other threads. - A thread can call wait() on a WaitableEvent, and this will suspend the - calling thread until another thread wakes it up by calling the signal() - method. -*/ -class WaitableEvent -{ -public: - //============================================================================== - /** Creates a WaitableEvent object. - - @param manualReset If this is false, the event will be reset automatically when the wait() - method is called. If manualReset is true, then once the event is signalled, - the only way to reset it will be by calling the reset() method. - - @param initiallySignaled If this is true then the event will be signaled when - the constructor returns. - */ - explicit WaitableEvent (bool manualReset = false, bool initiallySignaled = false); - - /** Destructor. - - If other threads are waiting on this object when it gets deleted, this - can cause nasty errors, so be careful! - */ - ~WaitableEvent(); - - WaitableEvent (WaitableEvent const&) = delete; - WaitableEvent& operator= (WaitableEvent const&) = delete; - - //============================================================================== - /** Suspends the calling thread until the event has been signalled. - - This will wait until the object's signal() method is called by another thread, - or until the timeout expires. - - After the event has been signalled, this method will return true and if manualReset - was set to false in the WaitableEvent's constructor, then the event will be reset. - - @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative - value will cause it to wait forever. - - @returns true if the object has been signalled, false if the timeout expires first. - @see signal, reset - */ - /** @{ */ - bool wait () const; // wait forever - // VFALCO TODO Change wait() to seconds instead of millis - bool wait (int timeOutMilliseconds) const; // DEPRECATED - /** @} */ - - //============================================================================== - /** Wakes up any threads that are currently waiting on this object. - - If signal() is called when nothing is waiting, the next thread to call wait() - will return immediately and reset the signal. - - If the WaitableEvent is manual reset, all current and future threads that wait upon this - object will be woken, until reset() is explicitly called. - - If the WaitableEvent is automatic reset, and one or more threads is waiting upon the object, - then one of them will be woken up. If no threads are currently waiting, then the next thread - to call wait() will be woken up. As soon as a thread is woken, the signal is automatically - reset. - - @see wait, reset - */ - void signal() const; - - //============================================================================== - /** Resets the event to an unsignalled state. - - If it's not already signalled, this does nothing. - */ - void reset() const; - -private: -#if BEAST_WINDOWS - void* handle; -#else - mutable pthread_cond_t condition; - mutable pthread_mutex_t mutex; - mutable bool triggered; - mutable bool manualReset; -#endif -}; - -} - -#endif diff --git a/beast/threads/impl/Stoppable.cpp b/beast/threads/impl/Stoppable.cpp deleted file mode 100644 index 10e730a2aa..0000000000 --- a/beast/threads/impl/Stoppable.cpp +++ /dev/null @@ -1,215 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2012, 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 -#include - -namespace beast { - -Stoppable::Stoppable (char const* name, RootStoppable& root) - : m_name (name) - , m_root (root) - , m_child (this) - , m_started (false) - , m_stopped (false) - , m_childrenStopped (false) -{ -} - -Stoppable::Stoppable (char const* name, Stoppable& parent) - : m_name (name) - , m_root (parent.m_root) - , m_child (this) - , m_started (false) - , m_stopped (false) - , m_childrenStopped (false) -{ - // Must not have stopping parent. - assert (! parent.isStopping()); - - parent.m_children.push_front (&m_child); -} - -Stoppable::~Stoppable () -{ - // Children must be stopped. - assert (!m_started || m_childrenStopped); -} - -bool Stoppable::isStopping() const -{ - return m_root.isStopping(); -} - -bool Stoppable::isStopped () const -{ - return m_stopped; -} - -bool Stoppable::areChildrenStopped () const -{ - return m_childrenStopped; -} - -void Stoppable::stopped () -{ - m_stoppedEvent.signal(); -} - -void Stoppable::onPrepare () -{ -} - -void Stoppable::onStart () -{ -} - -void Stoppable::onStop () -{ - stopped(); -} - -void Stoppable::onChildrenStopped () -{ -} - -//------------------------------------------------------------------------------ - -void Stoppable::prepareRecursive () -{ - for (Children::const_iterator iter (m_children.cbegin ()); - iter != m_children.cend(); ++iter) - iter->stoppable->prepareRecursive (); - onPrepare (); -} - -void Stoppable::startRecursive () -{ - onStart (); - for (Children::const_iterator iter (m_children.cbegin ()); - iter != m_children.cend(); ++iter) - iter->stoppable->startRecursive (); -} - -void Stoppable::stopAsyncRecursive (Journal j) -{ - using namespace std::chrono; - auto const start = high_resolution_clock::now(); - onStop (); - auto const ms = duration_cast( - high_resolution_clock::now() - start).count(); - -#ifdef NDEBUG - if (ms >= 10) - if (auto stream = j.fatal()) - stream << m_name << "::onStop took " << ms << "ms"; -#else - (void)ms; -#endif - - for (Children::const_iterator iter (m_children.cbegin ()); - iter != m_children.cend(); ++iter) - iter->stoppable->stopAsyncRecursive(j); -} - -void Stoppable::stopRecursive (Journal j) -{ - // Block on each child from the bottom of the tree up. - // - for (Children::const_iterator iter (m_children.cbegin ()); - iter != m_children.cend(); ++iter) - iter->stoppable->stopRecursive (j); - - // if we get here then all children have stopped - // - m_childrenStopped = true; - onChildrenStopped (); - - // Now block on this Stoppable. - // - bool const timedOut (! m_stoppedEvent.wait (1 * 1000)); // milliseconds - if (timedOut) - { - if (auto stream = j.error()) - stream << "Waiting for '" << m_name << "' to stop"; - m_stoppedEvent.wait (); - } - - // once we get here, we know the stoppable has stopped. - m_stopped = true; -} - -//------------------------------------------------------------------------------ - -RootStoppable::RootStoppable (char const* name) - : Stoppable (name, *this) - , m_prepared (false) - , m_calledStop (false) - , m_calledStopAsync (false) -{ -} - -bool RootStoppable::isStopping() const -{ - return m_calledStopAsync; -} - -void RootStoppable::prepare () -{ - if (m_prepared.exchange (true) == false) - prepareRecursive (); -} - -void RootStoppable::start () -{ - // Courtesy call to prepare. - if (m_prepared.exchange (true) == false) - prepareRecursive (); - - if (m_started.exchange (true) == false) - startRecursive (); -} - -void RootStoppable::stop (Journal j) -{ - // Must have a prior call to start() - assert (m_started); - - { - std::lock_guard lock(m_); - if (m_calledStop) - { - if (auto stream = j.warn()) - stream << "Stoppable::stop called again"; - return; - } - m_calledStop = true; - c_.notify_all(); - } - stopAsync (j); - stopRecursive (j); -} - -void RootStoppable::stopAsync(Journal j) -{ - if (m_calledStopAsync.exchange (true) == false) - stopAsyncRecursive(j); -} - -} diff --git a/beast/threads/impl/Stoppable.test.cpp b/beast/threads/impl/Stoppable.test.cpp deleted file mode 100644 index 842d3d6e5c..0000000000 --- a/beast/threads/impl/Stoppable.test.cpp +++ /dev/null @@ -1,451 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2012, 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 - -namespace beast { - -class Stoppable_test - : public unit_test::suite -{ -/* - R - / | \ - / | \ - A B C - / | \ /\ | - D E F G H I - | - J -*/ - unsigned count = 0; - - class D - : public Stoppable - { - Stoppable_test& test_; - public: - D(Stoppable& parent, Stoppable_test& test) - : Stoppable("D", parent) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 9, "D::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 0, "D::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 11, "D::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 2, "D::onChildrenStopped called out of order"); - } - }; - - class J - : public Stoppable - { - Stoppable_test& test_; - public: - J(Stoppable& parent, Stoppable_test& test) - : Stoppable("J", parent) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 7, "J::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 1, "J::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 10, "J::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 4, "J::onChildrenStopped called out of order"); - } - }; - - class E - : public Stoppable - { - J j_; - Stoppable_test& test_; - public: - E(Stoppable& parent, Stoppable_test& test) - : Stoppable("E", parent) - , j_(*this, test) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 8, "E::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 2, "E::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 9, "E::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 3, "E::onChildrenStopped called out of order"); - } - }; - - class F - : public Stoppable - { - Stoppable_test& test_; - public: - F(Stoppable& parent, Stoppable_test& test) - : Stoppable("F", parent) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 6, "F::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 3, "F::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 8, "F::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 5, "F::onChildrenStopped called out of order"); - } - }; - - class A - : public Stoppable - { - enum {running, please_stop, stopping, stopped}; - D d_; - E e_; - F f_; - Stoppable_test& test_; - std::atomic stop_; - public: - A(Stoppable& parent, Stoppable_test& test) - : Stoppable("A", parent) - , d_(*this, test) - , e_(*this, test) - , f_(*this, test) - , test_(test) - , stop_(running) - {} - ~A() - { - while (stop_ != stopped) - ; - } - - void run() - { - while (stop_ == running) - ; - stop_ = stopping; - } - - void onPrepare() override - { - test_.expect(++test_.count == 10, "A::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 4, "A::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 7, "A::onStop called out of order"); - } - - void onChildrenStopped() override - { - stop_ = please_stop; - while (stop_ != stopping) - ; - Stoppable::stopped(); - test_.expect(--test_.count == 1, "A::onChildrenStopped called out of order"); - stop_ = stopped; - } - }; - - class G - : public Stoppable - { - Stoppable_test& test_; - public: - G(Stoppable& parent, Stoppable_test& test) - : Stoppable("G", parent) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 4, "G::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 5, "G::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 6, "G::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 7, "G::onChildrenStopped called out of order"); - } - }; - - class H - : public Stoppable - { - Stoppable_test& test_; - public: - H(Stoppable& parent, Stoppable_test& test) - : Stoppable("H", parent) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 3, "H::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 6, "H::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 5, "H::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 8, "H::onChildrenStopped called out of order"); - } - }; - - class B - : public Stoppable - { - G g_; - H h_; - Stoppable_test& test_; - public: - B(Stoppable& parent, Stoppable_test& test) - : Stoppable("B", parent) - , g_(*this, test) - , h_(*this, test) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 5, "B::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 7, "B::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 4, "B::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 6, "B::onChildrenStopped called out of order"); - } - }; - - class I - : public Stoppable - { - Stoppable_test& test_; - public: - I(Stoppable& parent, Stoppable_test& test) - : Stoppable("I", parent) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 1, "I::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 8, "I::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 3, "I::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 10, "I::onChildrenStopped called out of order"); - } - }; - - class C - : public Stoppable - { - I i_; - Stoppable_test& test_; - public: - C(Stoppable& parent, Stoppable_test& test) - : Stoppable("C", parent) - , i_(*this, test) - , test_(test) - {} - - void onPrepare() override - { - test_.expect(++test_.count == 2, "C::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 9, "C::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 2, "C::onStop called out of order"); - } - - void onChildrenStopped() override - { - Stoppable::stopped(); - test_.expect(--test_.count == 9, "C::onChildrenStopped called out of order"); - } - }; - - class Root - : public RootStoppable - { - std::thread a_; - B b_; - C c_; - Stoppable_test& test_; - public: - Root(Stoppable_test& test) - : RootStoppable("R") - , a_(&A::run, std::make_unique(*this, test)) - , b_(*this, test) - , c_(*this, test) - , test_(test) - {} - - void run() - { - prepare(); - start(); - stop(Journal{}); - } - - void onPrepare() override - { - test_.expect(++test_.count == 11, "Root::onPrepare called out of order"); - } - - void onStart() override - { - test_.expect(--test_.count == 10, "Root::onStart called out of order"); - } - - void onStop() override - { - test_.expect(++test_.count == 1, "Root::onStop called out of order"); - } - - void onChildrenStopped() override - { - a_.join(); - Stoppable::stopped(); - test_.expect(--test_.count == 0, "Root::onChildrenStopped called out of order"); - } - }; - -public: - void run() - { - { - Root rt(*this); - rt.run(); - } - pass(); - } -}; - -BEAST_DEFINE_TESTSUITE(Stoppable,beast_core,beast); - -} diff --git a/beast/threads/impl/Thread.cpp b/beast/threads/impl/Thread.cpp deleted file mode 100644 index 8a25b68b25..0000000000 --- a/beast/threads/impl/Thread.cpp +++ /dev/null @@ -1,293 +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. -*/ -//============================================================================== - -#include -#include -#include - -#include -#include - -namespace beast { - -Thread::Thread (std::string const& threadName_) - : threadName (threadName_), - threadHandle (nullptr), - shouldExit (false) -{ -} - -Thread::~Thread() -{ - /* If your thread class's destructor has been called without first stopping the thread, that - means that this partially destructed object is still performing some work - and that's - probably a Bad Thing! - - To avoid this type of nastiness, always make sure you call stopThread() before or during - your subclass's destructor. - */ - assert (! isThreadRunning()); - - stopThread (); -} - -//============================================================================== -void Thread::threadEntryPoint() -{ - if (!threadName.empty ()) - setCurrentThreadName (threadName); - - if (startSuspensionEvent.wait (10000)) - run(); - - closeThreadHandle(); -} - -// used to wrap the incoming call from the platform-specific code -void beast_threadEntryPoint (void* userData) -{ - static_cast (userData)->threadEntryPoint(); -} - -//============================================================================== -void Thread::startThread() -{ - std::lock_guard sl (startStopLock); - - shouldExit = false; - - if (threadHandle == nullptr) - { - launchThread(); - startSuspensionEvent.signal(); - } -} - -bool Thread::isThreadRunning() const -{ - return threadHandle != nullptr; -} - -//============================================================================== -void Thread::signalThreadShouldExit() -{ - shouldExit = true; -} - -void Thread::waitForThreadToExit () const -{ - while (isThreadRunning()) - std::this_thread::sleep_for (std::chrono::milliseconds (10)); -} - -void Thread::stopThread () -{ - std::lock_guard sl (startStopLock); - - if (isThreadRunning()) - { - signalThreadShouldExit(); - notify(); - waitForThreadToExit (); - } -} - -void Thread::stopThreadAsync () -{ - std::lock_guard sl (startStopLock); - - if (isThreadRunning()) - { - signalThreadShouldExit(); - notify(); - } -} - -//============================================================================== -bool Thread::wait (const int timeOutMilliseconds) const -{ - return defaultEvent.wait (timeOutMilliseconds); -} - -void Thread::notify() const -{ - defaultEvent.signal(); -} - -} - -//------------------------------------------------------------------------------ - -#if BEAST_WINDOWS - -#include -#include -#include - -namespace beast { - -HWND beast_messageWindowHandle = 0; // (this is used by other parts of the codebase) - -void beast_threadEntryPoint (void*); - -static unsigned int __stdcall threadEntryProc (void* userData) -{ - if (beast_messageWindowHandle != 0) - AttachThreadInput (GetWindowThreadProcessId (beast_messageWindowHandle, 0), - GetCurrentThreadId(), TRUE); - - beast_threadEntryPoint (userData); - - _endthreadex (0); - return 0; -} - -void Thread::launchThread() -{ - unsigned int newThreadId; - threadHandle = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId); -} - -void Thread::closeThreadHandle() -{ - CloseHandle ((HANDLE) threadHandle); - threadHandle = 0; -} - -void Thread::setCurrentThreadName (std::string const& name) -{ - #if BEAST_DEBUG && BEAST_MSVC - struct - { - DWORD dwType; - LPCSTR szName; - DWORD dwThreadID; - DWORD dwFlags; - } info; - - info.dwType = 0x1000; - info.szName = name.c_str (); - info.dwThreadID = GetCurrentThreadId(); - info.dwFlags = 0; - - __try - { - RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info); - } - __except (EXCEPTION_CONTINUE_EXECUTION) - {} - #else - (void) name; - #endif -} - -} - -//------------------------------------------------------------------------------ - -#else - -#include -#include -#include - -#include -#if BEAST_BSD - // ??? -#elif BEAST_MAC || BEAST_IOS -#include -#include -#import -namespace beast{ -#include -} - -#else -#include - -#endif - -namespace beast { - -void beast_threadEntryPoint (void*); - -extern "C" void* threadEntryProcBeast (void*); -extern "C" void* threadEntryProcBeast (void* userData) -{ - BEAST_AUTORELEASEPOOL - { - #if BEAST_ANDROID - struct AndroidThreadScope - { - AndroidThreadScope() { threadLocalJNIEnvHolder.attach(); } - ~AndroidThreadScope() { threadLocalJNIEnvHolder.detach(); } - }; - - const AndroidThreadScope androidEnv; - #endif - - beast_threadEntryPoint (userData); - } - - return nullptr; -} - -void Thread::launchThread() -{ - threadHandle = 0; - pthread_t handle = 0; - - if (pthread_create (&handle, 0, threadEntryProcBeast, this) == 0) - { - pthread_detach (handle); - threadHandle = (void*) handle; - } -} - -void Thread::closeThreadHandle() -{ - threadHandle = 0; -} - -void Thread::setCurrentThreadName (std::string const& name) -{ - #if BEAST_IOS || (BEAST_MAC && defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5) - BEAST_AUTORELEASEPOOL - { - [[NSThread currentThread] setName: stringToNS (name)]; - } - #elif BEAST_LINUX - #if (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012 - pthread_setname_np (pthread_self(), name.c_str ()); - #else - prctl (PR_SET_NAME, name.c_str (), 0, 0, 0); - #endif - #endif -} - -} - -//------------------------------------------------------------------------------ - -#endif - diff --git a/beast/threads/impl/WaitableEvent.cpp b/beast/threads/impl/WaitableEvent.cpp deleted file mode 100644 index 05b85507a0..0000000000 --- a/beast/threads/impl/WaitableEvent.cpp +++ /dev/null @@ -1,168 +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. -*/ -//============================================================================== - -#include - -#if BEAST_WINDOWS - -#include -#undef check -#undef direct -#undef max -#undef min -#undef TYPE_BOOL - -namespace beast { - -WaitableEvent::WaitableEvent (const bool manualReset, bool initiallySignaled) - : handle (CreateEvent (0, manualReset ? TRUE : FALSE, initiallySignaled ? TRUE : FALSE, 0)) -{ -} - -WaitableEvent::~WaitableEvent() -{ - CloseHandle (handle); -} - -void WaitableEvent::signal() const -{ - SetEvent (handle); -} - -void WaitableEvent::reset() const -{ - ResetEvent (handle); -} - -bool WaitableEvent::wait () const -{ - return WaitForSingleObject (handle, INFINITE) == WAIT_OBJECT_0; -} - -bool WaitableEvent::wait (const int timeOutMs) const -{ - if (timeOutMs >= 0) - return WaitForSingleObject (handle, - (DWORD) timeOutMs) == WAIT_OBJECT_0; - return wait (); -} - -} - -#else - -namespace beast { - -WaitableEvent::WaitableEvent (const bool useManualReset, bool initiallySignaled) - : triggered (false), manualReset (useManualReset) -{ - pthread_cond_init (&condition, 0); - - pthread_mutexattr_t atts; - pthread_mutexattr_init (&atts); - #if ! BEAST_ANDROID - pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT); - #endif - pthread_mutex_init (&mutex, &atts); - - if (initiallySignaled) - signal (); -} - -WaitableEvent::~WaitableEvent() -{ - pthread_cond_destroy (&condition); - pthread_mutex_destroy (&mutex); -} - -bool WaitableEvent::wait () const -{ - return wait (-1); -} - -bool WaitableEvent::wait (const int timeOutMillisecs) const -{ - pthread_mutex_lock (&mutex); - - if (! triggered) - { - if (timeOutMillisecs < 0) - { - do - { - pthread_cond_wait (&condition, &mutex); - } - while (! triggered); - } - else - { - struct timeval now; - gettimeofday (&now, 0); - - struct timespec time; - time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000); - time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000; - - if (time.tv_nsec >= 1000000000) - { - time.tv_nsec -= 1000000000; - time.tv_sec++; - } - - do - { - if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT) - { - pthread_mutex_unlock (&mutex); - return false; - } - } - while (! triggered); - } - } - - if (! manualReset) - triggered = false; - - pthread_mutex_unlock (&mutex); - return true; -} - -void WaitableEvent::signal() const -{ - pthread_mutex_lock (&mutex); - triggered = true; - pthread_cond_broadcast (&condition); - pthread_mutex_unlock (&mutex); -} - -void WaitableEvent::reset() const -{ - pthread_mutex_lock (&mutex); - triggered = false; - pthread_mutex_unlock (&mutex); -} - -} - -#endif diff --git a/beast/threads/semaphore.h b/beast/threads/semaphore.h deleted file mode 100644 index a0bff2fe5f..0000000000 --- a/beast/threads/semaphore.h +++ /dev/null @@ -1,86 +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_THREADS_SEMAPHORE_H_INCLUDED -#define BEAST_THREADS_SEMAPHORE_H_INCLUDED - -#include -#include - -namespace beast { - -template -class basic_semaphore -{ -private: - using scoped_lock = std::unique_lock ; - - Mutex m_mutex; - CondVar m_cond; - std::size_t m_count; - -public: - using size_type = std::size_t; - - /** 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; - } -}; - -using semaphore = basic_semaphore ; -} - -#endif - diff --git a/beast/utility/type_name.h b/beast/type_name.h similarity index 96% rename from beast/utility/type_name.h rename to beast/type_name.h index 039a3c86c3..59222ee4fc 100644 --- a/beast/utility/type_name.h +++ b/beast/type_name.h @@ -17,8 +17,8 @@ */ //============================================================================== -#ifndef BEAST_UTILITY_TYPE_NAME_H_INCLUDED -#define BEAST_UTILITY_TYPE_NAME_H_INCLUDED +#ifndef BEAST_TYPE_NAME_H_INCLUDED +#define BEAST_TYPE_NAME_H_INCLUDED #include #include diff --git a/beast/container/const_container.h b/beast/unit_test/const_container.h similarity index 96% rename from beast/container/const_container.h rename to beast/unit_test/const_container.h index accd168fcb..2bf093c738 100644 --- a/beast/container/const_container.h +++ b/beast/unit_test/const_container.h @@ -17,8 +17,8 @@ */ //============================================================================== -#ifndef BEAST_CONTAINER_CONST_CONTAINER_H_INCLUDED -#define BEAST_CONTAINER_CONST_CONTAINER_H_INCLUDED +#ifndef BEAST_UNIT_TEST_CONST_CONTAINER_H_INCLUDED +#define BEAST_UNIT_TEST_CONST_CONTAINER_H_INCLUDED namespace beast { diff --git a/beast/unit_test/results.h b/beast/unit_test/results.h index 3f45840b73..125b897020 100644 --- a/beast/unit_test/results.h +++ b/beast/unit_test/results.h @@ -20,7 +20,7 @@ #ifndef BEAST_UNIT_TEST_RESULTS_H_INCLUDED #define BEAST_UNIT_TEST_RESULTS_H_INCLUDED -#include +#include #include #include diff --git a/beast/unit_test/suite_list.h b/beast/unit_test/suite_list.h index 26581e3478..b552d4e36c 100644 --- a/beast/unit_test/suite_list.h +++ b/beast/unit_test/suite_list.h @@ -21,11 +21,8 @@ #define BEAST_UNIT_TEST_SUITE_LIST_H_INCLUDED #include - -#include - +#include #include -//#include #include #include #include diff --git a/beast/module/core/diagnostic/UnitTestUtilities.h b/beast/unit_test/temp_dir.h similarity index 54% rename from beast/module/core/diagnostic/UnitTestUtilities.h rename to beast/unit_test/temp_dir.h index d625a5a33a..030dcfcbe6 100644 --- a/beast/module/core/diagnostic/UnitTestUtilities.h +++ b/beast/unit_test/temp_dir.h @@ -17,57 +17,67 @@ */ //============================================================================== -#ifndef BEAST_MODULE_CORE_DIAGNOSTIC_UNITTESTUTILITIES_H_INCLUDED -#define BEAST_MODULE_CORE_DIAGNOSTIC_UNITTESTUTILITIES_H_INCLUDED +#ifndef BEAST_UNITTEST_TEMP_DIR_H_INCLUDED +#define BEAST_UNITTEST_TEMP_DIR_H_INCLUDED #include #include namespace beast { -namespace UnitTestUtilities { -class TempDirectory +/** RAII temporary directory. + + The directory and all its contents are deleted when + the instance of `temp_dir` is destroyed. +*/ +class temp_dir { -public: - TempDirectory () - { - auto const tempDir = - boost::filesystem::temp_directory_path(); + boost::filesystem::path path_; +public: +#if ! GENERATING_DOCS + temp_dir(const temp_dir&) = delete; + temp_dir& operator=(const temp_dir&) = delete; +#endif + + /// Construct a temporary directory. + temp_dir() + { + auto const dir = + boost::filesystem::temp_directory_path(); do { - tempPath = - tempDir / boost::filesystem::unique_path(); - } while (boost::filesystem::exists(tempPath)); - - boost::filesystem::create_directory (tempPath); + path_ = + dir / boost::filesystem::unique_path(); + } + while(boost::filesystem::exists(path_)); + boost::filesystem::create_directory (path_); } - ~TempDirectory() + /// Destroy a temporary directory. + ~temp_dir() { - boost::filesystem::remove_all (tempPath); + boost::filesystem::remove_all (path_); } - /** Returns the native path for the temporary folder */ - std::string path() const + /// Get the native path for the temporary directory + std::string + path() const { - return tempPath.string(); + return path_.string(); } - /** Returns the native for the given file */ - std::string file (std::string const& name) const + /** Get the native path for the a file. + + The file does not need to exist. + */ + std::string + file(std::string const& name) const { - return (tempPath / name).string(); + return (path_ / name).string(); } - - TempDirectory(const TempDirectory&) = delete; - TempDirectory& operator=(const TempDirectory&) = delete; - -private: - boost::filesystem::path tempPath; }; -} // UnitTestUtilities } // beast #endif diff --git a/beast/config/compiler/Clang.h b/beast/unity/beast_clock_unity.cpp similarity index 89% rename from beast/config/compiler/Clang.h rename to beast/unity/beast_clock_unity.cpp index 25896af5b7..cb54279ce3 100644 --- a/beast/config/compiler/Clang.h +++ b/beast/unity/beast_clock_unity.cpp @@ -17,4 +17,5 @@ */ //============================================================================== -// Clang compiler configuration +#include +#include diff --git a/beast/config/SelectStdlibConfig.h b/beast/unity/beast_crypto_unity.cpp similarity index 95% rename from beast/config/SelectStdlibConfig.h rename to beast/unity/beast_crypto_unity.cpp index ccc99a2a56..fdb2e106dd 100644 --- a/beast/config/SelectStdlibConfig.h +++ b/beast/unity/beast_crypto_unity.cpp @@ -17,5 +17,5 @@ */ //============================================================================== -// Ideas from boost +#include diff --git a/beast/unity/hash_unity.cpp b/beast/unity/beast_hash_unity.cpp similarity index 100% rename from beast/unity/hash_unity.cpp rename to beast/unity/beast_hash_unity.cpp diff --git a/beast/config/compiler/Gcc.h b/beast/unity/beast_streams_unity.cpp similarity index 93% rename from beast/config/compiler/Gcc.h rename to beast/unity/beast_streams_unity.cpp index 7b594b0858..7de0dea249 100644 --- a/beast/config/compiler/Gcc.h +++ b/beast/unity/beast_streams_unity.cpp @@ -17,4 +17,4 @@ */ //============================================================================== -// GNU C++ compiler configuration +#include diff --git a/beast/config/compiler/Intel.h b/beast/unity/beast_test_unity.cpp similarity index 94% rename from beast/config/compiler/Intel.h rename to beast/unity/beast_test_unity.cpp index 3e5d3cdbc7..654d00821f 100644 --- a/beast/config/compiler/Intel.h +++ b/beast/unity/beast_test_unity.cpp @@ -17,4 +17,4 @@ */ //============================================================================== -// Intel compiler configuration +#include diff --git a/beast/utility/Debug.h b/beast/utility/Debug.h deleted file mode 100644 index 69ab73f41b..0000000000 --- a/beast/utility/Debug.h +++ /dev/null @@ -1,66 +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_UTILITY_DEBUG_H_INCLUDED -#define BEAST_UTILITY_DEBUG_H_INCLUDED - -#include - -namespace beast { - -// Auxiliary outines for debugging - -namespace Debug -{ - -// -// These control the MSVC C Runtime Debug heap. -// -// The calls currently do nothing on other platforms. -// - -/** Calls checkHeap() at every allocation and deallocation. -*/ -extern void setAlwaysCheckHeap (bool bAlwaysCheck); - -/** Keep freed memory blocks in the heap's linked list, assign them the - _FREE_BLOCK type, and fill them with the byte value 0xDD. -*/ -extern void setHeapDelayedFree (bool bDelayedFree); - -/** Perform automatic leak checking at program exit through a call to - dumpMemoryLeaks() and generate an error report if the application - failed to free all the memory it allocated. -*/ -extern void setHeapReportLeaks (bool bReportLeaks); - -/** Report all memory blocks which have not been freed. -*/ -extern void reportLeaks (); - -/** Confirms the integrity of the memory blocks allocated in the - debug heap (debug version only. -*/ -extern void checkHeap (); - -} - -} - -#endif diff --git a/beast/utility/Journal.h b/beast/utility/Journal.h deleted file mode 100644 index 810daf923f..0000000000 --- a/beast/utility/Journal.h +++ /dev/null @@ -1,360 +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_UTILITY_JOURNAL_H_INCLUDED -#define BEAST_UTILITY_JOURNAL_H_INCLUDED - -#include -#include - -namespace beast { - -/** A namespace for easy access to logging severity values. */ -namespace severities -{ - /** Severity level / threshold of a Journal message. */ - enum Severity - { - kAll = 0, - - kTrace = kAll, - kDebug, - kInfo, - kWarning, - kError, - kFatal, - - kDisabled, - kNone = kDisabled - }; -} - -/** A generic endpoint for log messages. - - The Journal has a few simple goals: - - * To be light-weight and copied by value. - * To allow logging statements to be left in source code. - * The logging is controlled at run-time based on a logging threshold. - - It is advisable to check Journal::active(level) prior to formatting log - text. Doing so sidesteps expensive text formatting when the results - will not be sent to the log. -*/ -class Journal -{ -public: - class Sink; - -private: - // Severity level / threshold of a Journal message. - using Severity = severities::Severity; - - Sink& m_sink; - -public: - //-------------------------------------------------------------------------- - - /** Abstraction for the underlying message destination. */ - class Sink - { - protected: - Sink () = delete; - explicit Sink(Sink const& sink) = default; - Sink (Severity thresh, bool console); - Sink& operator= (Sink const& lhs) = delete; - - public: - virtual ~Sink () = 0; - - /** Returns `true` if text at the passed severity produces output. */ - virtual bool active (Severity level) const; - - /** Returns `true` if a message is also written to the Output Window (MSVC). */ - virtual bool console () const; - - /** Set whether messages are also written to the Output Window (MSVC). */ - virtual void console (bool output); - - /** Returns the minimum severity level this sink will report. */ - virtual Severity threshold() const; - - /** Set the minimum severity this sink will report. */ - virtual void threshold (Severity thresh); - - /** Write text to the sink at the specified severity. - A conforming implementation will not write the text if the passed - level is below the current threshold(). - */ - virtual void write (Severity level, std::string const& text) = 0; - - private: - Severity thresh_; - bool m_console; - }; - -static_assert(std::is_default_constructible::value == false, ""); -static_assert(std::is_copy_constructible::value == false, ""); -static_assert(std::is_move_constructible::value == false, ""); -static_assert(std::is_copy_assignable::value == false, ""); -static_assert(std::is_move_assignable::value == false, ""); -static_assert(std::is_nothrow_destructible::value == true, ""); - - /** Returns a Sink which does nothing. */ - static Sink& getNullSink (); - - //-------------------------------------------------------------------------- - - class Stream; - -private: - /* Scoped ostream-based container for writing messages to a Journal. */ - class ScopedStream - { - public: - ScopedStream (ScopedStream const& other) - : ScopedStream (other.m_sink, other.m_level) - { } - - ScopedStream (Sink& sink, Severity level); - - template - ScopedStream (Stream const& stream, T const& t); - - ScopedStream ( - Stream const& stream, std::ostream& manip (std::ostream&)); - - ScopedStream& operator= (ScopedStream const&) = delete; - - ~ScopedStream (); - - std::ostringstream& ostream () const - { - return m_ostream; - } - - std::ostream& operator<< ( - std::ostream& manip (std::ostream&)) const; - - template - std::ostream& operator<< (T const& t) const; - - private: - Sink& m_sink; - Severity const m_level; - std::ostringstream mutable m_ostream; - }; - -static_assert(std::is_default_constructible::value == false, ""); -static_assert(std::is_copy_constructible::value == true, ""); -static_assert(std::is_move_constructible::value == true, ""); -static_assert(std::is_copy_assignable::value == false, ""); -static_assert(std::is_move_assignable::value == false, ""); -static_assert(std::is_nothrow_destructible::value == true, ""); - - //-------------------------------------------------------------------------- -public: - /** Provide a light-weight way to check active() before string formatting */ - class Stream - { - public: - /** Create a stream which produces no output. */ - Stream () - : m_sink (getNullSink()) - , m_level (severities::kDisabled) - { } - - /** Create stream that writes at the given level. - - Constructor is inlined so checking active() very inexpensive. - */ - Stream (Sink& sink, Severity level) - : m_sink (sink) - , m_level (level) - { - assert (m_level < severities::kDisabled); - } - - /** Construct or copy another Stream. */ - Stream (Stream const& other) - : Stream (other.m_sink, other.m_level) - { } - - Stream& operator= (Stream const& other) = delete; - - /** Returns the Sink that this Stream writes to. */ - Sink& sink() const - { - return m_sink; - } - - /** Returns the Severity level of messages this Stream reports. */ - Severity level() const - { - return m_level; - } - - /** Returns `true` if sink logs anything at this stream's level. */ - /** @{ */ - bool active() const - { - return m_sink.active (m_level); - } - - explicit - operator bool() const - { - return active(); - } - /** @} */ - - /** Output stream support. */ - /** @{ */ - ScopedStream operator<< (std::ostream& manip (std::ostream&)) const; - - template - ScopedStream operator<< (T const& t) const; - /** @} */ - - private: - Sink& m_sink; - Severity m_level; - }; - -static_assert(std::is_default_constructible::value == true, ""); -static_assert(std::is_copy_constructible::value == true, ""); -static_assert(std::is_move_constructible::value == true, ""); -static_assert(std::is_copy_assignable::value == false, ""); -static_assert(std::is_move_assignable::value == false, ""); -static_assert(std::is_nothrow_destructible::value == true, ""); - - //-------------------------------------------------------------------------- - - /** Create a journal that writes to the null sink. */ - Journal () - : Journal (getNullSink()) - { } - - /** Create a journal that writes to the specified sink. */ - explicit Journal (Sink& sink) - : m_sink (sink) - { } - - /** Create a journal from another journal. */ - Journal (Journal const& other) - : Journal (other.m_sink) - { } - - // Disallowed. - Journal& operator= (Journal const& other) = delete; - - /** Destroy the journal. */ - ~Journal () = default; - - /** Returns the Sink associated with this Journal. */ - Sink& sink() const - { - return m_sink; - } - - /** Returns a stream for this sink, with the specified severity level. */ - Stream stream (Severity level) const - { - return Stream (m_sink, level); - } - - /** Returns `true` if any message would be logged at this severity level. - For a message to be logged, the severity must be at or above the - sink's severity threshold. - */ - bool active (Severity level) const - { - return m_sink.active (level); - } - - /** Severity stream access functions. */ - /** @{ */ - Stream trace() const - { - return { m_sink, severities::kTrace }; - } - - Stream debug() const - { - return { m_sink, severities::kDebug }; - } - - Stream info() const - { - return { m_sink, severities::kInfo }; - } - - Stream warn() const - { - return { m_sink, severities::kWarning }; - } - - Stream error() const - { - return { m_sink, severities::kError }; - } - - Stream fatal() const - { - return { m_sink, severities::kFatal }; - } - /** @} */ -}; - -static_assert(std::is_default_constructible::value == true, ""); -static_assert(std::is_copy_constructible::value == true, ""); -static_assert(std::is_move_constructible::value == true, ""); -static_assert(std::is_copy_assignable::value == false, ""); -static_assert(std::is_move_assignable::value == false, ""); -static_assert(std::is_nothrow_destructible::value == true, ""); - -//------------------------------------------------------------------------------ - -template -Journal::ScopedStream::ScopedStream (Journal::Stream const& stream, T const& t) - : ScopedStream (stream.sink(), stream.level()) -{ - m_ostream << t; -} - -template -std::ostream& -Journal::ScopedStream::operator<< (T const& t) const -{ - m_ostream << t; - return m_ostream; -} - -//------------------------------------------------------------------------------ - -template -Journal::ScopedStream -Journal::Stream::operator<< (T const& t) const -{ - return ScopedStream (*this, t); -} - -} // beast - -#endif diff --git a/beast/utility/PropertyStream.h b/beast/utility/PropertyStream.h deleted file mode 100644 index ce0be64006..0000000000 --- a/beast/utility/PropertyStream.h +++ /dev/null @@ -1,360 +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_UTILITY_PROPERTYSTREAM_H_INCLUDED -#define BEAST_UTILITY_PROPERTYSTREAM_H_INCLUDED - -#include - -#include -#include -#include -#include -#include - -namespace beast { - -//------------------------------------------------------------------------------ - -/** Abstract stream with RAII containers that produce a property tree. */ -class PropertyStream -{ -public: - class Map; - class Set; - class Source; - - PropertyStream (); - virtual ~PropertyStream (); - -protected: - virtual void map_begin () = 0; - virtual void map_begin (std::string const& key) = 0; - virtual void map_end () = 0; - - virtual void add (std::string const& key, std::string const& value) = 0; - - void add (std::string const& key, char const* value) - { - add (key, std::string (value)); - } - - template - void lexical_add (std::string const &key, Value value) - { - std::stringstream ss; - ss << value; - add (key, ss.str()); - } - - virtual void add (std::string const& key, bool value); - virtual void add (std::string const& key, char value); - virtual void add (std::string const& key, signed char value); - virtual void add (std::string const& key, unsigned char value); - virtual void add (std::string const& key, wchar_t value); -#if 0 - virtual void add (std::string const& key, char16_t value); - virtual void add (std::string const& key, char32_t value); -#endif - virtual void add (std::string const& key, short value); - virtual void add (std::string const& key, unsigned short value); - virtual void add (std::string const& key, int value); - virtual void add (std::string const& key, unsigned int value); - virtual void add (std::string const& key, long value); - virtual void add (std::string const& key, unsigned long value); - virtual void add (std::string const& key, long long value); - virtual void add (std::string const& key, unsigned long long value); - virtual void add (std::string const& key, float value); - virtual void add (std::string const& key, double value); - virtual void add (std::string const& key, long double value); - - virtual void array_begin () = 0; - virtual void array_begin (std::string const& key) = 0; - virtual void array_end () = 0; - - virtual void add (std::string const& value) = 0; - - void add (char const* value) - { - add (std::string (value)); - } - - template - void lexical_add (Value value) - { - std::stringstream ss; - ss << value; - add (ss.str()); - } - - virtual void add (bool value); - virtual void add (char value); - virtual void add (signed char value); - virtual void add (unsigned char value); - virtual void add (wchar_t value); -#if 0 - virtual void add (char16_t value); - virtual void add (char32_t value); -#endif - virtual void add (short value); - virtual void add (unsigned short value); - virtual void add (int value); - virtual void add (unsigned int value); - virtual void add (long value); - virtual void add (unsigned long value); - virtual void add (long long value); - virtual void add (unsigned long long value); - virtual void add (float value); - virtual void add (double value); - virtual void add (long double value); - -private: - class Item; - class Proxy; -}; - -//------------------------------------------------------------------------------ -// -// Item -// -//------------------------------------------------------------------------------ - -class PropertyStream::Item : public List ::Node -{ -public: - explicit Item (Source* source); - Source& source() const; - Source* operator-> () const; - Source& operator* () const; -private: - Source* m_source; -}; - -//------------------------------------------------------------------------------ -// -// Proxy -// -//------------------------------------------------------------------------------ - -class PropertyStream::Proxy -{ -private: - Map const* m_map; - std::string m_key; - std::ostringstream mutable m_ostream; - -public: - Proxy (Map const& map, std::string const& key); - Proxy (Proxy const& other); - ~Proxy (); - - template - Proxy& operator= (Value value); - - std::ostream& operator<< (std::ostream& manip (std::ostream&)) const; - - template - std::ostream& operator<< (T const& t) const - { - return m_ostream << t; - } -}; - -//------------------------------------------------------------------------------ -// -// Map -// -//------------------------------------------------------------------------------ - -class PropertyStream::Map -{ -private: - PropertyStream& m_stream; - -public: - explicit Map (PropertyStream& stream); - explicit Map (Set& parent); - Map (std::string const& key, Map& parent); - Map (std::string const& key, PropertyStream& stream); - ~Map (); - - Map(Map const&) = delete; - Map& operator= (Map const&) = delete; - - PropertyStream& stream(); - PropertyStream const& stream() const; - - template - void add (std::string const& key, Value value) const - { - m_stream.add (key, value); - } - - template - void add (Key key, Value value) const - { - std::stringstream ss; - ss << key; - add (ss.str(), value); - } - - Proxy operator[] (std::string const& key); - - Proxy operator[] (char const* key) - { return Proxy (*this, key); } - - template - Proxy operator[] (Key key) const - { - std::stringstream ss; - ss << key; - return Proxy (*this, ss.str()); - } -}; - -//-------------------------------------------------------------------------- - -template -PropertyStream::Proxy& PropertyStream::Proxy::operator= (Value value) -{ - m_map->add (m_key, value); - return *this; -} - -//-------------------------------------------------------------------------- -// -// Set -// -//------------------------------------------------------------------------------ - -class PropertyStream::Set -{ -private: - PropertyStream& m_stream; - -public: - Set (std::string const& key, Map& map); - Set (std::string const& key, PropertyStream& stream); - ~Set (); - - Set (Set const&) = delete; - Set& operator= (Set const&) = delete; - - PropertyStream& stream(); - PropertyStream const& stream() const; - - template - void add (Value value) const - { m_stream.add (value); } -}; - -//------------------------------------------------------------------------------ -// -// Source -// -//------------------------------------------------------------------------------ - -/** Subclasses can be called to write to a stream and have children. */ -class PropertyStream::Source -{ -private: - std::string const m_name; - std::recursive_mutex lock_; - Item item_; - Source* parent_; - List children_; - -public: - explicit Source (std::string const& name); - ~Source (); - - Source (Source const&) = delete; - Source& operator= (Source const&) = delete; - - /** Returns the name of this source. */ - std::string const& name() const; - - /** Add a child source. */ - void add (Source& source); - - /** Add a child source by pointer. - The source pointer is returned so it can be used in ctor-initializers. - */ - template - Derived* add (Derived* child) - { - add (*static_cast (child)); - return child; - } - - /** Remove a child source from this Source. */ - void remove (Source& child); - - /** Remove all child sources from this Source. */ - void removeAll (); - - /** Write only this Source to the stream. */ - void write_one (PropertyStream& stream); - - /** write this source and all its children recursively to the stream. */ - void write (PropertyStream& stream); - - /** Parse the path and write the corresponding Source and optional children. - If the source is found, it is written. If the wildcard character '*' - exists as the last character in the path, then all the children are - written recursively. - */ - void write (PropertyStream& stream, std::string const& path); - - /** Parse the dot-delimited Source path and return the result. - The first value will be a pointer to the Source object corresponding - to the given path. If no Source object exists, then the first value - will be nullptr and the second value will be undefined. - The second value is a boolean indicating whether or not the path string - specifies the wildcard character '*' as the last character. - - print statement examples - "parent.child" prints child and all of its children - "parent.child." start at the parent and print down to child - "parent.grandchild" prints nothing- grandchild not direct discendent - "parent.grandchild." starts at the parent and prints down to grandchild - "parent.grandchild.*" starts at parent, print through grandchild children - */ - std::pair find (std::string path); - - Source* find_one_deep (std::string const& name); - PropertyStream::Source* find_path(std::string path); - PropertyStream::Source* find_one(std::string const& name); - - static bool peel_leading_slash (std::string* path); - static bool peel_trailing_slashstar (std::string* path); - static std::string peel_name(std::string* path); - - - //-------------------------------------------------------------------------- - - /** Subclass override. - The default version does nothing. - */ - virtual void onWrite (Map&); -}; - -} - -#endif diff --git a/beast/utility/Utility.unity.cpp b/beast/utility/Utility.unity.cpp deleted file mode 100644 index 49e4b05bae..0000000000 --- a/beast/utility/Utility.unity.cpp +++ /dev/null @@ -1,32 +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. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include -#include -#include - -#include -#include -#include -#include -#include diff --git a/beast/utility/WrappedSink.h b/beast/utility/WrappedSink.h deleted file mode 100644 index f45804f221..0000000000 --- a/beast/utility/WrappedSink.h +++ /dev/null @@ -1,96 +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_UTILITY_WRAPPEDSINK_H_INCLUDED -#define BEAST_UTILITY_WRAPPEDSINK_H_INCLUDED - -#include - -namespace beast { - -/** Wraps a Journal::Sink to prefix its output with a string. */ - -// A WrappedSink both is a Sink and has a Sink: -// o It inherits from Sink so it has the correct interface. -// o It has a sink (reference) so it preserves the passed write() behavior. -// The data inherited from the base class is ignored. -class WrappedSink : public beast::Journal::Sink -{ -private: - beast::Journal::Sink& sink_; - std::string prefix_; - -public: - explicit - WrappedSink (beast::Journal::Sink& sink, std::string const& prefix = "") - : Sink (sink) - , sink_(sink) - , prefix_(prefix) - { - } - - explicit - WrappedSink (beast::Journal const& journal, std::string const& prefix = "") - : WrappedSink (journal.sink(), prefix) - { - } - - void prefix (std::string const& s) - { - prefix_ = s; - } - - bool - active (beast::severities::Severity level) const override - { - return sink_.active (level); - } - - bool - console () const override - { - return sink_.console (); - } - - void console (bool output) override - { - sink_.console (output); - } - - beast::severities::Severity - threshold() const override - { - return sink_.threshold(); - } - - void threshold (beast::severities::Severity thresh) override - { - sink_.threshold (thresh); - } - - void write (beast::severities::Severity level, std::string const& text) override - { - using beast::Journal; - sink_.write (level, prefix_ + text); - } -}; - -} - -#endif diff --git a/beast/utility/Zero.h b/beast/utility/Zero.h deleted file mode 100644 index c09c183216..0000000000 --- a/beast/utility/Zero.h +++ /dev/null @@ -1,163 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Tom Ritchford - - 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_UTILITY_ZERO_H_INCLUDED -#define BEAST_UTILITY_ZERO_H_INCLUDED - -#include - -// VS2013 SP1 fails with decltype return -#define BEAST_NO_ZERO_AUTO_RETURN 1 - -namespace beast { - -/** Zero allows classes to offer efficient comparisons to zero. - - Zero is a struct to allow classes to efficiently compare with zero without - requiring an rvalue construction. - - It's often the case that we have classes which combine a number and a unit. - In such cases, comparisons like t > 0 or t != 0 make sense, but comparisons - like t > 1 or t != 1 do not. - - The class Zero allows such comparisons to be easily made. - - The comparing class T either needs to have a method called signum() which - returns a positive number, 0, or a negative; or there needs to be a signum - function which resolves in the namespace which takes an instance of T and - returns a positive, zero or negative number. -*/ - -struct Zero -{ -}; - -namespace { -static BEAST_CONSTEXPR Zero zero{}; -} - -/** Default implementation of signum calls the method on the class. */ -template -#if BEAST_NO_ZERO_AUTO_RETURN -int signum(T const& t) -#else -auto signum(T const& t) -> decltype(t.signum()) -#endif -{ - return t.signum(); -} - -namespace detail { -namespace zero_helper { - -// For argument dependent lookup to function properly, calls to signum must -// be made from a namespace that does not include overloads of the function.. -template -#if BEAST_NO_ZERO_AUTO_RETURN -int call_signum (T const& t) -#else -auto call_signum(T const& t) -> decltype(t.signum()) -#endif -{ - return signum(t); -} - -} // zero_helper -} // detail - -// Handle operators where T is on the left side using signum. - -template -bool operator==(T const& t, Zero) -{ - return detail::zero_helper::call_signum(t) == 0; -} - -template -bool operator!=(T const& t, Zero) -{ - return detail::zero_helper::call_signum(t) != 0; -} - -template -bool operator<(T const& t, Zero) -{ - return detail::zero_helper::call_signum(t) < 0; -} - -template -bool operator>(T const& t, Zero) -{ - return detail::zero_helper::call_signum(t) > 0; -} - -template -bool operator>=(T const& t, Zero) -{ - return detail::zero_helper::call_signum(t) >= 0; -} - -template -bool operator<=(T const& t, Zero) -{ - return detail::zero_helper::call_signum(t) <= 0; -} - -// Handle operators where T is on the right side by -// reversing the operation, so that T is on the left side. - -template -bool operator==(Zero, T const& t) -{ - return t == zero; -} - -template -bool operator!=(Zero, T const& t) -{ - return t != zero; -} - -template -bool operator<(Zero, T const& t) -{ - return t > zero; -} - -template -bool operator>(Zero, T const& t) -{ - return t < zero; -} - -template -bool operator>=(Zero, T const& t) -{ - return t <= zero; -} - -template -bool operator<=(Zero, T const& t) -{ - return t >= zero; -} - -} // beast - -#endif diff --git a/beast/utility/hash_pair.h b/beast/utility/hash_pair.h deleted file mode 100644 index 74c3bd44e6..0000000000 --- a/beast/utility/hash_pair.h +++ /dev/null @@ -1,70 +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_UTILITY_HASH_PAIR_H_INCLUDED -#define BEAST_UTILITY_HASH_PAIR_H_INCLUDED - -#include -#include - -#include -#include - -namespace std { - -/** Specialization of std::hash for any std::pair type. */ -template -struct hash > - : private boost::base_from_member , 0> - , private boost::base_from_member , 1> -{ -private: - using first_hash = boost::base_from_member , 0>; - using second_hash = boost::base_from_member , 1>; - -public: - hash () - { - } - - hash (std::hash const& first_hash_, - std::hash const& second_hash_) - : first_hash (first_hash_) - , second_hash (second_hash_) - { - } - - std::size_t operator() (std::pair const& value) - { - std::size_t result (first_hash::member (value.first)); - boost::hash_combine (result, second_hash::member (value.second)); - return result; - } - - std::size_t operator() (std::pair const& value) const - { - std::size_t result (first_hash::member (value.first)); - boost::hash_combine (result, second_hash::member (value.second)); - return result; - } -}; - -} - -#endif diff --git a/beast/utility/impl/Debug.cpp b/beast/utility/impl/Debug.cpp deleted file mode 100644 index 42a8f6bdc9..0000000000 --- a/beast/utility/impl/Debug.cpp +++ /dev/null @@ -1,160 +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 -#include -#include - -namespace beast { - -namespace Debug { - -//------------------------------------------------------------------------------ - -#if BEAST_MSVC && defined (_DEBUG) - -#if BEAST_CHECK_MEMORY_LEAKS -struct DebugFlagsInitialiser -{ - DebugFlagsInitialiser() - { - // Activate leak checks on exit in the MSVC Debug CRT (C Runtime) - // - _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); - } -}; - -static DebugFlagsInitialiser debugFlagsInitialiser; -#endif - -void setAlwaysCheckHeap (bool bAlwaysCheck) -{ - int flags = _CrtSetDbgFlag (_CRTDBG_REPORT_FLAG); - - if (bAlwaysCheck) flags |= _CRTDBG_CHECK_ALWAYS_DF; // on - else flags &= ~_CRTDBG_CHECK_ALWAYS_DF; // off - - _CrtSetDbgFlag (flags); -} - -void setHeapDelayedFree (bool bDelayedFree) -{ - int flags = _CrtSetDbgFlag (_CRTDBG_REPORT_FLAG); - - if (bDelayedFree) flags |= _CRTDBG_DELAY_FREE_MEM_DF; // on - else flags &= ~_CRTDBG_DELAY_FREE_MEM_DF; // off - - _CrtSetDbgFlag (flags); -} - -void setHeapReportLeaks (bool bReportLeaks) -{ - int flags = _CrtSetDbgFlag (_CRTDBG_REPORT_FLAG); - - if (bReportLeaks) flags |= _CRTDBG_LEAK_CHECK_DF; // on - else flags &= ~_CRTDBG_LEAK_CHECK_DF; // off - - _CrtSetDbgFlag (flags); -} - -void reportLeaks () -{ - _CrtDumpMemoryLeaks (); -} - -void checkHeap () -{ - _CrtCheckMemory (); -} - -//------------------------------------------------------------------------------ - -#else - -void setAlwaysCheckHeap (bool) -{ -} - -void setHeapDelayedFree (bool) -{ -} - -void setHeapReportLeaks (bool) -{ -} - -void reportLeaks () -{ -} - -void checkHeap () -{ -} - -#endif - -} - -//------------------------------------------------------------------------------ - -// A simple unit test to determine the diagnostic settings in a build. -// -class Debug_test : public unit_test::suite -{ -public: - static int envDebug () - { - #ifdef _DEBUG - return 1; - #else - return 0; - #endif - } - - static int beastDebug () - { - #ifdef BEAST_DEBUG - return BEAST_DEBUG; - #else - return 0; - #endif - } - - static int beastForceDebug () - { - #ifdef BEAST_FORCE_DEBUG - return BEAST_FORCE_DEBUG; - #else - return 0; - #endif - } - - void run () - { - log << "_DEBUG = " << envDebug (); - log << "BEAST_DEBUG = " << beastDebug (); - log << "BEAST_FORCE_DEBUG = " << beastForceDebug (); - log << "sizeof(std::size_t) = " << sizeof(std::size_t); - pass (); - } -}; - -BEAST_DEFINE_TESTSUITE(Debug,utility,beast); - -} diff --git a/beast/utility/impl/Journal.cpp b/beast/utility/impl/Journal.cpp deleted file mode 100644 index 48de8cdc05..0000000000 --- a/beast/utility/impl/Journal.cpp +++ /dev/null @@ -1,155 +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 -#include - -namespace beast { - -//------------------------------------------------------------------------------ - -// A Sink that does nothing. -class NullJournalSink : public Journal::Sink -{ -public: - NullJournalSink () - : Sink (severities::kDisabled, false) - { } - - ~NullJournalSink() override = default; - - bool active (severities::Severity) const override - { - return false; - } - - bool console() const override - { - return false; - } - - void console (bool) override - { - } - - severities::Severity threshold() const override - { - return severities::kDisabled; - } - - void threshold (severities::Severity) override - { - } - - void write (severities::Severity, std::string const&) override - { - } -}; - -//------------------------------------------------------------------------------ - -Journal::Sink& Journal::getNullSink () -{ - static NullJournalSink sink; - return sink; -} - -//------------------------------------------------------------------------------ - -Journal::Sink::Sink (Severity thresh, bool console) - : thresh_ (thresh) - , m_console (console) -{ -} - -Journal::Sink::~Sink () -{ -} - -bool Journal::Sink::active (Severity level) const -{ - return level >= thresh_; -} - -bool Journal::Sink::console () const -{ - return m_console; -} - -void Journal::Sink::console (bool output) -{ - m_console = output; -} - -severities::Severity Journal::Sink::threshold () const -{ - return thresh_; -} - -void Journal::Sink::threshold (Severity thresh) -{ - thresh_ = thresh; -} - -//------------------------------------------------------------------------------ - -Journal::ScopedStream::ScopedStream (Sink& sink, Severity level) - : m_sink (sink) - , m_level (level) -{ - // Modifiers applied from all ctors - m_ostream - << std::boolalpha - << std::showbase; -} - -Journal::ScopedStream::ScopedStream ( - Stream const& stream, std::ostream& manip (std::ostream&)) - : ScopedStream (stream.sink(), stream.level()) -{ - m_ostream << manip; -} - -Journal::ScopedStream::~ScopedStream () -{ - std::string const& s (m_ostream.str()); - if (! s.empty ()) - { - if (s == "\n") - m_sink.write (m_level, ""); - else - m_sink.write (m_level, s); - } -} - -std::ostream& Journal::ScopedStream::operator<< (std::ostream& manip (std::ostream&)) const -{ - return m_ostream << manip; -} - -//------------------------------------------------------------------------------ - -Journal::ScopedStream Journal::Stream::operator<< ( - std::ostream& manip (std::ostream&)) const -{ - return ScopedStream (*this, manip); -} - -} // beast - diff --git a/beast/utility/impl/PropertyStream.cpp b/beast/utility/impl/PropertyStream.cpp deleted file mode 100644 index c66f016bf5..0000000000 --- a/beast/utility/impl/PropertyStream.cpp +++ /dev/null @@ -1,776 +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 -#include - -#include -#include -#include - -namespace beast { - -//------------------------------------------------------------------------------ -// -// Item -// -//------------------------------------------------------------------------------ - -PropertyStream::Item::Item (Source* source) - : m_source (source) -{ -} - -PropertyStream::Source& PropertyStream::Item::source() const -{ - return *m_source; -} - -PropertyStream::Source* PropertyStream::Item::operator-> () const -{ - return &source(); -} - -PropertyStream::Source& PropertyStream::Item::operator* () const -{ - return source(); -} - -//------------------------------------------------------------------------------ -// -// Proxy -// -//------------------------------------------------------------------------------ - -PropertyStream::Proxy::Proxy ( - Map const& map, std::string const& key) - : m_map (&map) - , m_key (key) -{ -} - -PropertyStream::Proxy::Proxy (Proxy const& other) - : m_map (other.m_map) - , m_key (other.m_key) -{ -} - -PropertyStream::Proxy::~Proxy () -{ - std::string const s (m_ostream.str()); - if (! s.empty()) - m_map->add (m_key, s); -} - -std::ostream& PropertyStream::Proxy::operator<< ( - std::ostream& manip (std::ostream&)) const -{ - return m_ostream << manip; -} - -//------------------------------------------------------------------------------ -// -// Map -// -//------------------------------------------------------------------------------ - -PropertyStream::Map::Map (PropertyStream& stream) - : m_stream (stream) -{ -} - -PropertyStream::Map::Map (Set& parent) - : m_stream (parent.stream()) -{ - m_stream.map_begin (); -} - -PropertyStream::Map::Map (std::string const& key, Map& map) - : m_stream (map.stream()) -{ - m_stream.map_begin (key); -} - -PropertyStream::Map::Map (std::string const& key, PropertyStream& stream) - : m_stream (stream) -{ - m_stream.map_begin (key); -} - -PropertyStream::Map::~Map () -{ - m_stream.map_end (); -} - -PropertyStream& PropertyStream::Map::stream() -{ - return m_stream; -} - -PropertyStream const& PropertyStream::Map::stream() const -{ - return m_stream; -} - -PropertyStream::Proxy PropertyStream::Map::operator[] (std::string const& key) -{ - return Proxy (*this, key); -} - -//------------------------------------------------------------------------------ -// -// Set -// -//------------------------------------------------------------------------------ - -PropertyStream::Set::Set (std::string const& key, Map& map) - : m_stream (map.stream()) -{ - m_stream.array_begin (key); -} - -PropertyStream::Set::Set (std::string const& key, PropertyStream& stream) - : m_stream (stream) -{ - m_stream.array_begin (key); -} - -PropertyStream::Set::~Set () -{ - m_stream.array_end (); -} - -PropertyStream& PropertyStream::Set::stream() -{ - return m_stream; -} - -PropertyStream const& PropertyStream::Set::stream() const -{ - return m_stream; -} - -//------------------------------------------------------------------------------ -// -// Source -// -//------------------------------------------------------------------------------ - -PropertyStream::Source::Source (std::string const& name) - : m_name (name) - , item_ (this) - , parent_ (nullptr) -{ -} - -PropertyStream::Source::~Source () -{ - std::lock_guard _(lock_); - if (parent_ != nullptr) - parent_->remove (*this); - removeAll (); -} - -std::string const& PropertyStream::Source::name () const -{ - return m_name; -} - -void PropertyStream::Source::add (Source& source) -{ - std::lock(lock_, source.lock_); - std::lock_guard lk1(lock_, std::adopt_lock); - std::lock_guard lk2(source.lock_, std::adopt_lock); - - assert (source.parent_ == nullptr); - children_.push_back (source.item_); - source.parent_ = this; -} - -void PropertyStream::Source::remove (Source& child) -{ - std::lock(lock_, child.lock_); - std::lock_guard lk1(lock_, std::adopt_lock); - std::lock_guard lk2(child.lock_, std::adopt_lock); - - assert (child.parent_ == this); - children_.erase ( - children_.iterator_to ( - child.item_)); - child.parent_ = nullptr; -} - -void PropertyStream::Source::removeAll () -{ - std::lock_guard _(lock_); - for (auto iter = children_.begin(); iter != children_.end(); ) - { - std::lock_guard _cl((*iter)->lock_); - remove (*(*iter)); - } -} - -//------------------------------------------------------------------------------ - -void PropertyStream::Source::write_one (PropertyStream& stream) -{ - Map map (m_name, stream); - onWrite (map); -} - -void PropertyStream::Source::write (PropertyStream& stream) -{ - Map map (m_name, stream); - onWrite (map); - - std::lock_guard _(lock_); - - for (auto& child : children_) - child.source().write (stream); -} - -void PropertyStream::Source::write (PropertyStream& stream, std::string const& path) -{ - std::pair result (find (path)); - - if (result.first == nullptr) - return; - - if (result.second) - result.first->write (stream); - else - result.first->write_one (stream); -} - -std::pair PropertyStream::Source::find (std::string path) -{ - bool const deep (peel_trailing_slashstar (&path)); - bool const rooted (peel_leading_slash (&path)); - Source* source (this); - if (! path.empty()) - { - if (! rooted) - { - std::string const name (peel_name (&path)); - source = find_one_deep (name); - if (source == nullptr) - return std::make_pair (nullptr, deep); - } - source = source->find_path (path); - } - return std::make_pair (source, deep); -} - -bool PropertyStream::Source::peel_leading_slash (std::string* path) -{ - if (! path->empty() && path->front() == '/') - { - *path = std::string (path->begin() + 1, path->end()); - return true; - } - return false; -} - -bool PropertyStream::Source::peel_trailing_slashstar (std::string* path) -{ - bool found(false); - if (path->empty()) - return false; - if (path->back() == '*') - { - found = true; - path->pop_back(); - } - if(! path->empty() && path->back() == '/') - path->pop_back(); - return found; -} - -std::string PropertyStream::Source::peel_name (std::string* path) -{ - if (path->empty()) - return ""; - - std::string::const_iterator first = (*path).begin(); - std::string::const_iterator last = (*path).end(); - std::string::const_iterator pos (std::find (first, last, '/')); - std::string s (first, pos); - - if (pos != last) - *path = std::string (pos+1, last); - else - *path = std::string (); - - return s; -} - -// Recursive search through the whole tree until name is found -PropertyStream::Source* PropertyStream::Source::find_one_deep (std::string const& name) -{ - Source* found = find_one (name); - if (found != nullptr) - return found; - - std::lock_guard _(lock_); - for (auto& s : children_) - { - found = s.source().find_one_deep (name); - if (found != nullptr) - return found; - } - return nullptr; -} - -PropertyStream::Source* PropertyStream::Source::find_path (std::string path) -{ - if (path.empty()) - return this; - Source* source (this); - do - { - std::string const name (peel_name (&path)); - if(name.empty ()) - break; - source = source->find_one(name); - } - while (source != nullptr); - return source; -} - -// This function only looks at immediate children -// If no immediate children match, then return nullptr -PropertyStream::Source* PropertyStream::Source::find_one (std::string const& name) -{ - std::lock_guard _(lock_); - for (auto& s : children_) - { - if (s.source().m_name == name) - return &s.source(); - } - return nullptr; -} - -void PropertyStream::Source::onWrite (Map&) -{ -} - -//------------------------------------------------------------------------------ -// -// PropertyStream -// -//------------------------------------------------------------------------------ - -PropertyStream::PropertyStream () -{ -} - -PropertyStream::~PropertyStream () -{ -} - -void PropertyStream::add (std::string const& key, bool value) -{ - if (value) - add (key, "true"); - else - add (key, "false"); -} - -void PropertyStream::add (std::string const& key, char value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, signed char value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, unsigned char value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, wchar_t value) -{ - lexical_add (key, value); -} - -#if 0 -void PropertyStream::add (std::string const& key, char16_t value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, char32_t value) -{ - lexical_add (key, value); -} -#endif - -void PropertyStream::add (std::string const& key, short value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, unsigned short value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, int value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, unsigned int value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, long value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, unsigned long value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, long long value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, unsigned long long value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, float value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, double value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (std::string const& key, long double value) -{ - lexical_add (key, value); -} - -void PropertyStream::add (bool value) -{ - if (value) - add ("true"); - else - add ("false"); -} - -void PropertyStream::add (char value) -{ - lexical_add (value); -} - -void PropertyStream::add (signed char value) -{ - lexical_add (value); -} - -void PropertyStream::add (unsigned char value) -{ - lexical_add (value); -} - -void PropertyStream::add (wchar_t value) -{ - lexical_add (value); -} - -#if 0 -void PropertyStream::add (char16_t value) -{ - lexical_add (value); -} - -void PropertyStream::add (char32_t value) -{ - lexical_add (value); -} -#endif - -void PropertyStream::add (short value) -{ - lexical_add (value); -} - -void PropertyStream::add (unsigned short value) -{ - lexical_add (value); -} - -void PropertyStream::add (int value) -{ - lexical_add (value); -} - -void PropertyStream::add (unsigned int value) -{ - lexical_add (value); -} - -void PropertyStream::add (long value) -{ - lexical_add (value); -} - -void PropertyStream::add (unsigned long value) -{ - lexical_add (value); -} - -void PropertyStream::add (long long value) -{ - lexical_add (value); -} - -void PropertyStream::add (unsigned long long value) -{ - lexical_add (value); -} - -void PropertyStream::add (float value) -{ - lexical_add (value); -} - -void PropertyStream::add (double value) -{ - lexical_add (value); -} - -void PropertyStream::add (long double value) -{ - lexical_add (value); -} - -//------------------------------------------------------------------------------ - -class PropertyStream_test : public unit_test::suite -{ -public: - using Source = PropertyStream::Source; - - void test_peel_name (std::string s, std::string const& expected, - std::string const& expected_remainder) - { - try - { - std::string const peeled_name = Source::peel_name (&s); - expect (peeled_name == expected); - expect (s == expected_remainder); - } - catch (...) - { - fail ("unhandled exception");; - } - } - - void test_peel_leading_slash (std::string s, std::string const& expected, - bool should_be_found) - { - try - { - bool const found (Source::peel_leading_slash (&s)); - expect (found == should_be_found); - expect (s == expected); - } - catch(...) - { - fail ("unhandled exception");; - } - } - - void test_peel_trailing_slashstar (std::string s, - std::string const& expected_remainder, bool should_be_found) - { - try - { - bool const found (Source::peel_trailing_slashstar (&s)); - expect (found == should_be_found); - expect (s == expected_remainder); - } - catch (...) - { - fail ("unhandled exception");; - } - } - - void test_find_one (Source& root, Source* expected, std::string const& name) - { - try - { - Source* source (root.find_one (name)); - expect (source == expected); - } - catch (...) - { - fail ("unhandled exception");; - } - } - - void test_find_path (Source& root, std::string const& path, - Source* expected) - { - try - { - Source* source (root.find_path (path)); - expect (source == expected); - } - catch (...) - { - fail ("unhandled exception");; - } - } - - void test_find_one_deep (Source& root, std::string const& name, - Source* expected) - { - try - { - Source* source (root.find_one_deep (name)); - expect (source == expected); - } - catch(...) - { - fail ("unhandled exception");; - } - } - - void test_find (Source& root, std::string path, Source* expected, - bool expected_star) - { - try - { - auto const result (root.find (path)); - expect (result.first == expected); - expect (result.second == expected_star); - } - catch (...) - { - fail ("unhandled exception");; - } - } - - void run() - { - Source a ("a"); - Source b ("b"); - Source c ("c"); - Source d ("d"); - Source e ("e"); - Source f ("f"); - Source g ("g"); - - // - // a { b { d { f }, e }, c { g } } - // - - a.add ( b ); - a.add ( c ); - c.add ( g ); - b.add ( d ); - b.add ( e ); - d.add ( f ); - - testcase ("peel_name"); - test_peel_name ("a", "a", ""); - test_peel_name ("foo/bar", "foo", "bar"); - test_peel_name ("foo/goo/bar", "foo", "goo/bar"); - test_peel_name ("", "", ""); - - testcase ("peel_leading_slash"); - test_peel_leading_slash ("foo/", "foo/", false); - test_peel_leading_slash ("foo", "foo", false); - test_peel_leading_slash ("/foo/", "foo/", true); - test_peel_leading_slash ("/foo", "foo", true); - - testcase ("peel_trailing_slashstar"); - test_peel_trailing_slashstar ("/foo/goo/*", "/foo/goo", true); - test_peel_trailing_slashstar ("foo/goo/*", "foo/goo", true); - test_peel_trailing_slashstar ("/foo/goo/", "/foo/goo", false); - test_peel_trailing_slashstar ("foo/goo", "foo/goo", false); - test_peel_trailing_slashstar ("", "", false); - test_peel_trailing_slashstar ("/", "", false); - test_peel_trailing_slashstar ("/*", "", true); - test_peel_trailing_slashstar ("//", "/", false); - test_peel_trailing_slashstar ("**", "*", true); - test_peel_trailing_slashstar ("*/", "*", false); - - testcase ("find_one"); - test_find_one (a, &b, "b"); - test_find_one (a, nullptr, "d"); - test_find_one (b, &e, "e"); - test_find_one (d, &f, "f"); - - testcase ("find_path"); - test_find_path (a, "a", nullptr); - test_find_path (a, "e", nullptr); - test_find_path (a, "a/b", nullptr); - test_find_path (a, "a/b/e", nullptr); - test_find_path (a, "b/e/g", nullptr); - test_find_path (a, "b/e/f", nullptr); - test_find_path (a, "b", &b); - test_find_path (a, "b/e", &e); - test_find_path (a, "b/d/f", &f); - - testcase ("find_one_deep"); - test_find_one_deep (a, "z", nullptr); - test_find_one_deep (a, "g", &g); - test_find_one_deep (a, "b", &b); - test_find_one_deep (a, "d", &d); - test_find_one_deep (a, "f", &f); - - testcase ("find"); - test_find (a, "", &a, false); - test_find (a, "*", &a, true); - test_find (a, "/b", &b, false); - test_find (a, "b", &b, false); - test_find (a, "d", &d, false); - test_find (a, "/b*", &b, true); - test_find (a, "b*", &b, true); - test_find (a, "d*", &d, true); - test_find (a, "/b/*", &b, true); - test_find (a, "b/*", &b, true); - test_find (a, "d/*", &d, true); - test_find (a, "a", nullptr, false); - test_find (a, "/d", nullptr, false); - test_find (a, "/d*", nullptr, true); - test_find (a, "/d/*", nullptr, true); - } -}; - -BEAST_DEFINE_TESTSUITE(PropertyStream,utility,beast); - -} - diff --git a/beast/utility/make_lock.h b/beast/utility/make_lock.h deleted file mode 100644 index 76f9d7ff1d..0000000000 --- a/beast/utility/make_lock.h +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2015, Howard Hinnant - - 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_UTILITY_MAKE_LOCK_H_INCLUDED -#define BEAST_UTILITY_MAKE_LOCK_H_INCLUDED - -#include -#include - -namespace beast { - -template -inline -std::unique_lock -make_lock(Mutex& mutex, Args&&... args) -{ - return std::unique_lock(mutex, std::forward(args)...); -} - -} // beast - -#endif diff --git a/beast/utility/maybe_const.h b/beast/utility/maybe_const.h deleted file mode 100644 index 1de13373c4..0000000000 --- a/beast/utility/maybe_const.h +++ /dev/null @@ -1,42 +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_UTILITY_MAYBE_CONST_H_INCLUDED -#define BEAST_UTILITY_MAYBE_CONST_H_INCLUDED - -#include - -namespace beast { - -/** Makes T const or non const depending on a bool. */ -template -struct maybe_const -{ - using type = typename std::conditional ::type const, - typename std::remove_const ::type>::type; -}; - -/** Alias for omitting `typename`. */ -template -using maybe_const_t = typename maybe_const ::type; - -} - -#endif diff --git a/beast/utility/tagged_integer.h b/beast/utility/tagged_integer.h deleted file mode 100644 index fb79a5741f..0000000000 --- a/beast/utility/tagged_integer.h +++ /dev/null @@ -1,243 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Nikolaos D. Bougalis - - 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_UTILITY_TAGGED_INTEGER_H_INCLUDED -#define BEAST_UTILITY_TAGGED_INTEGER_H_INCLUDED - -#include - -#include -#include -#include -#include - -namespace beast { - -/** A type-safe wrap around standard unsigned integral types - - The tag is used to implement type safety, catching mismatched types at - compile time. Multiple instantiations wrapping the same underlying integral - type are distinct types (distinguished by tag) and will not interoperate. - - A tagged_integer supports all the comparison operators that are available - for the underlying integral type. It only supports a subset of arithmetic - operators, restricting mutation to only safe and meaningful types. -*/ -template -class tagged_integer -{ -private: - static_assert (std::is_unsigned ::value, - "The specified Int type must be unsigned"); - - Int m_value; - -public: - using value_type = Int; - using tag_type = Tag; - - tagged_integer() = default; - - template < - class OtherInt, - class = typename std::enable_if < - std::is_integral ::value && - sizeof (OtherInt) <= sizeof (Int) - >::type - > - explicit - /* constexpr */ - tagged_integer (OtherInt value) noexcept - : m_value (value) - { - } - - // Arithmetic operators - tagged_integer& - operator++ () noexcept - { - ++m_value; - return *this; - } - - tagged_integer - operator++ (int) noexcept - { - tagged_integer orig (*this); - ++(*this); - return orig; - } - - tagged_integer& - operator-- () noexcept - { - --m_value; - return *this; - } - - tagged_integer - operator-- (int) noexcept - { - tagged_integer orig (*this); - --(*this); - return orig; - } - - template - typename std::enable_if < - std::is_integral ::value && - sizeof (OtherInt) <= sizeof (Int), - tagged_integer >::type& - operator+= (OtherInt rhs) noexcept - { - m_value += rhs; - return *this; - } - - template - typename std::enable_if < - std::is_integral ::value && - sizeof (OtherInt) <= sizeof (Int), - tagged_integer >::type& - operator-= (OtherInt rhs) noexcept - { - m_value -= rhs; - return *this; - } - - template - friend - typename std::enable_if < - std::is_integral ::value && - sizeof (OtherInt) <= sizeof (Int), - tagged_integer >::type - operator+ (tagged_integer const& lhs, - OtherInt rhs) noexcept - { - return tagged_integer (lhs.m_value + rhs); - } - - template - friend - typename std::enable_if < - std::is_integral ::value && - sizeof (OtherInt) <= sizeof (Int), - tagged_integer >::type - operator+ (OtherInt lhs, - tagged_integer const& rhs) noexcept - { - return tagged_integer (lhs + rhs.m_value); - } - - template - friend - typename std::enable_if < - std::is_integral ::value && - sizeof (OtherInt) <= sizeof (Int), - tagged_integer >::type - operator- (tagged_integer const& lhs, - OtherInt rhs) noexcept - { - return tagged_integer (lhs.m_value - rhs); - } - - friend - Int - operator- (tagged_integer const& lhs, - tagged_integer const& rhs) noexcept - { - return lhs.m_value - rhs.m_value; - } - - // Comparison operators - friend - bool - operator== (tagged_integer const& lhs, - tagged_integer const& rhs) noexcept - { - return lhs.m_value == rhs.m_value; - } - - friend - bool - operator!= (tagged_integer const& lhs, - tagged_integer const& rhs) noexcept - { - return lhs.m_value != rhs.m_value; - } - - friend - bool - operator< (tagged_integer const& lhs, - tagged_integer const& rhs) noexcept - { - return lhs.m_value < rhs.m_value; - } - - friend - bool - operator<= (tagged_integer const& lhs, - tagged_integer const& rhs) noexcept - { - return lhs.m_value <= rhs.m_value; - } - - friend - bool - operator> (tagged_integer const& lhs, - tagged_integer const& rhs) noexcept - { - return lhs.m_value > rhs.m_value; - } - - friend - bool - operator>= (tagged_integer const& lhs, - tagged_integer const& rhs) noexcept - { - return lhs.m_value >= rhs.m_value; - } - - friend - std::ostream& - operator<< (std::ostream& s, tagged_integer const& t) - { - s << t.m_value; - return s; - } - - friend - std::istream& - operator>> (std::istream& s, tagged_integer& t) - { - s >> t.m_value; - return s; - } -}; - -template -struct is_contiguously_hashable, HashAlgorithm> - : public is_contiguously_hashable -{ -}; - -} - -#endif - diff --git a/beast/utility/tests/Journal.test.cpp b/beast/utility/tests/Journal.test.cpp deleted file mode 100644 index 8a9d08ee34..0000000000 --- a/beast/utility/tests/Journal.test.cpp +++ /dev/null @@ -1,103 +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 -#include - -namespace beast { - -class Journal_test : public unit_test::suite -{ -public: - class TestSink : public Journal::Sink - { - private: - int m_count; - - public: - TestSink() - : Sink (severities::kWarning, false) - , m_count(0) - { - } - - int - count() const - { - return m_count; - } - - void - reset() - { - m_count = 0; - } - - void - write (severities::Severity level, std::string const&) override - { - if (level >= threshold()) - ++m_count; - } - }; - - void run () - { - TestSink sink; - - using namespace beast::severities; - sink.threshold(kInfo); - - Journal j(sink); - - j.trace() << " "; - expect(sink.count() == 0); - j.debug() << " "; - expect(sink.count() == 0); - j.info() << " "; - expect(sink.count() == 1); - j.warn() << " "; - expect(sink.count() == 2); - j.error() << " "; - expect(sink.count() == 3); - j.fatal() << " "; - expect(sink.count() == 4); - - sink.reset(); - - sink.threshold(kDebug); - - j.trace() << " "; - expect(sink.count() == 0); - j.debug() << " "; - expect(sink.count() == 1); - j.info() << " "; - expect(sink.count() == 2); - j.warn() << " "; - expect(sink.count() == 3); - j.error() << " "; - expect(sink.count() == 4); - j.fatal() << " "; - expect(sink.count() == 5); - } -}; - -BEAST_DEFINE_TESTSUITE(Journal,utility,beast); - -} // beast diff --git a/beast/utility/tests/Zero.test.cpp b/beast/utility/tests/Zero.test.cpp deleted file mode 100644 index 64cd0c41fe..0000000000 --- a/beast/utility/tests/Zero.test.cpp +++ /dev/null @@ -1,142 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Nikolaos D. Bougalis - - 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 - -#include - -namespace beast { - -struct adl_tester {}; - -int signum (adl_tester) -{ - return 0; -} - - -namespace detail { - -struct adl_tester2 {}; - -int signum (adl_tester2) -{ - return 0; -} - -} // detail - -class Zero_test : public beast::unit_test::suite -{ -private: - struct IntegerWrapper - { - int value; - - IntegerWrapper (int v) - : value (v) - { - } - - int signum() const - { - return value; - } - }; - -public: - void expect_same(bool result, bool correct, char const* message) - { - expect(result == correct, message); - } - - void - test_lhs_zero (IntegerWrapper x) - { - expect_same (x >= zero, x.signum () >= 0, - "lhs greater-than-or-equal-to"); - expect_same (x > zero, x.signum () > 0, - "lhs greater than"); - expect_same (x == zero, x.signum () == 0, - "lhs equal to"); - expect_same (x != zero, x.signum () != 0, - "lhs not equal to"); - expect_same (x < zero, x.signum () < 0, - "lhs less than"); - expect_same (x <= zero, x.signum () <= 0, - "lhs less-than-or-equal-to"); - } - - void - test_lhs_zero () - { - testcase ("lhs zero"); - - test_lhs_zero(-7); - test_lhs_zero(0); - test_lhs_zero(32); - } - - void - test_rhs_zero (IntegerWrapper x) - { - expect_same (zero >= x, 0 >= x.signum (), - "rhs greater-than-or-equal-to"); - expect_same (zero > x, 0 > x.signum (), - "rhs greater than"); - expect_same (zero == x, 0 == x.signum (), - "rhs equal to"); - expect_same (zero != x, 0 != x.signum (), - "rhs not equal to"); - expect_same (zero < x, 0 < x.signum (), - "rhs less than"); - expect_same (zero <= x, 0 <= x.signum (), - "rhs less-than-or-equal-to"); - } - - void - test_rhs_zero () - { - testcase ("rhs zero"); - - test_rhs_zero(-4); - test_rhs_zero(0); - test_rhs_zero(64); - } - - void - test_adl () - { - expect (adl_tester{} == zero, "ADL failure!"); - expect (detail::adl_tester2{} == zero, "ADL failure!"); - } - - void - run() - { - test_lhs_zero (); - test_rhs_zero (); - test_adl (); - } - -}; - -BEAST_DEFINE_TESTSUITE(Zero, types, beast); - -} diff --git a/beast/utility/tests/tagged_integer.test.cpp b/beast/utility/tests/tagged_integer.test.cpp deleted file mode 100644 index 32f4d58df3..0000000000 --- a/beast/utility/tests/tagged_integer.test.cpp +++ /dev/null @@ -1,154 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Nikolaos D. Bougalis - - 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 BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include - -#include -#include - -namespace beast { - -class tagged_integer_test - : public unit_test::suite -{ -private: - struct Tag1 { }; - struct Tag2 { }; - - using TagInt1 = tagged_integer ; - using TagInt2 = tagged_integer ; - using TagInt3 = tagged_integer ; - - // Check construction of tagged_integers - static_assert (std::is_constructible::value, - "TagInt1 should be constructible using a std::uint32_t"); - - static_assert (!std::is_constructible::value, - "TagInt1 should not be constructible using a std::uint64_t"); - - static_assert (std::is_constructible::value, - "TagInt3 should be constructible using a std::uint32_t"); - - static_assert (std::is_constructible::value, - "TagInt3 should be constructible using a std::uint64_t"); - - // Check assignment of tagged_integers - static_assert (!std::is_assignable::value, - "TagInt1 should not be assignable with a std::uint32_t"); - - static_assert (!std::is_assignable::value, - "TagInt1 should not be assignable with a std::uint64_t"); - - static_assert (!std::is_assignable::value, - "TagInt3 should not be assignable with a std::uint32_t"); - - static_assert (!std::is_assignable::value, - "TagInt3 should not be assignable with a std::uint64_t"); - - static_assert (std::is_assignable::value, - "TagInt1 should be assignable with a TagInt1"); - - static_assert (!std::is_assignable::value, - "TagInt1 should not be assignable with a TagInt2"); - - static_assert (std::is_assignable::value, - "TagInt3 should be assignable with a TagInt1"); - - static_assert (!std::is_assignable::value, - "TagInt1 should not be assignable with a TagInt3"); - - static_assert (!std::is_assignable::value, - "TagInt3 should not be assignable with a TagInt1"); - - // Check convertibility of tagged_integers - static_assert (!std::is_convertible::value, - "std::uint32_t should not be convertible to a TagInt1"); - - static_assert (!std::is_convertible::value, - "std::uint32_t should not be convertible to a TagInt3"); - - static_assert (!std::is_convertible::value, - "std::uint64_t should not be convertible to a TagInt3"); - - static_assert (!std::is_convertible::value, - "std::uint64_t should not be convertible to a TagInt2"); - - static_assert (!std::is_convertible::value, - "TagInt1 should not be convertible to TagInt2"); - - static_assert (!std::is_convertible::value, - "TagInt1 should not be convertible to TagInt3"); - - static_assert (!std::is_convertible::value, - "TagInt2 should not be convertible to a TagInt3"); - -public: - void run () - { - TagInt1 const zero (0); - TagInt1 const one (1); - - testcase ("Comparison Operators"); - - expect (zero >= zero, "Should be greater than or equal"); - expect (zero == zero, "Should be equal"); - - expect (one > zero, "Should be greater"); - expect (one >= zero, "Should be greater than or equal"); - expect (one != zero, "Should not be equal"); - - unexpected (one < zero, "Should be greater"); - unexpected (one <= zero, "Should not be greater than or equal"); - unexpected (one == zero, "Should not be equal"); - - testcase ("Arithmetic Operators"); - - TagInt1 tmp; - - tmp = zero + 0u; - expect (tmp == zero, "Should be equal"); - - tmp = 1u + zero; - expect (tmp == one, "Should be equal"); - - expect(--tmp == zero, "Should be equal"); - expect(tmp++ == zero, "Should be equal"); - expect(tmp == one, "Should be equal"); - - expect(tmp-- == one, "Should be equal"); - expect(tmp == zero, "Should be equal"); - expect(++tmp == one, "Should be equal"); - - tmp = zero; - - tmp += 1u; - expect(tmp == one, "Should be equal"); - - tmp -= 1u; - expect(tmp == zero, "Should be equal"); - } -}; - -BEAST_DEFINE_TESTSUITE(tagged_integer,utility,beast); - -} // beast diff --git a/beast/utility/tests/weak_fn.test.cpp b/beast/utility/tests/weak_fn.test.cpp deleted file mode 100644 index 27ff3fa4c7..0000000000 --- a/beast/utility/tests/weak_fn.test.cpp +++ /dev/null @@ -1,147 +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 -#include - -namespace beast { - -class weak_fn_test : public beast::unit_test::suite -{ -public: - struct T - { - bool& called_; - - explicit - T (bool& called) - : called_(called) - { - } - - void - fv() - { - called_ = true; - } - - void - fi(int i) - { - called_ = true; - } - - void - fis(int, std::string) - { - called_ = true; - } - - int - fri() - { - called_ = true; - return 2; - } - }; - - void - run() - { - { - bool called = false; - auto const p = std::make_shared(called); - std::bind(weak_fn(&T::fv, p))(); - expect(called); - } - - { - bool called = false; - auto p = std::make_shared(called); - auto call = std::bind(weak_fn(&T::fv, p)); - p.reset(); - call(); - expect(! called); - } - - { - bool called = false; - auto p = std::make_shared(called); - std::bind(weak_fn(&T::fi, p), 1)(); - expect(called); - } - - { - bool called = false; - auto p = std::make_shared(called); - std::bind(weak_fn(&T::fi, p), - std::placeholders::_1)(1); - expect(called); - } - - { - bool called = false; - auto p = std::make_shared(called); - std::bind(weak_fn(&T::fis, p), - 1, std::placeholders::_1)("foo"); - expect(called); - } - - { - bool called = false; - auto p = std::make_shared(called); - try - { - auto call = std::bind(weak_fn(&T::fis, p, throw_if_invalid<>()), - 1, std::placeholders::_1); - p.reset(); - call("foo"); - fail(); - } - catch(std::bad_weak_ptr const&) - { - expect(! called); - } - } - - { - bool called = false; - auto p = std::make_shared(called); - expect(std::bind(weak_fn(&T::fri, p))() == 2); - expect(called); - } - - { - bool called = false; - auto p = std::make_shared(called); - auto call = std::bind(weak_fn(&T::fv, p, - [&called]() - { - called = true; - })); - p.reset(); - call(); - expect(called); - } - } -}; - -BEAST_DEFINE_TESTSUITE(weak_fn,asio,beast); - -} diff --git a/beast/weak_fn.h b/beast/weak_fn.h deleted file mode 100644 index f3e78cc4fa..0000000000 --- a/beast/weak_fn.h +++ /dev/null @@ -1,175 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, 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_WEAK_FN_H_INCLUDED -#define BEAST_WEAK_FN_H_INCLUDED - -#include -#include - -// Original version: -// http://lists.boost.org/Archives/boost/att-189469/weak_fn.hpp -// -// This work was adapted from source code with this copyright notice: -// -// weak_fun.hpp -// -// Copyright (c) 2009 Artyom Beilis -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -namespace beast { - -// Policy throws if weak pointer is expired -template -struct throw_if_invalid -{ - V operator()() const - { - throw std::bad_weak_ptr(); - } -}; - -// Policy returns a value if weak pointer is expired -template -struct return_default_if_invalid -{ - return_default_if_invalid() - : def_value_() - { } - - return_default_if_invalid(V def_value) - : def_value_(def_value) - { } - - V operator()() const - { - return def_value_; - } - -private: - V def_value_; -}; - -// Policy does nothing if weak pointer is expired -template -struct ignore_if_invalid -{ - V operator()() const - { - return V(); - } -}; - -template -using default_invalid_policy = ignore_if_invalid; - -namespace detail { - -template -class weak_binder - : private beast::empty_base_optimization -{ -private: - using member_type = R (T::*)(Args...); - using pointer_type = std::weak_ptr; - using shared_type = std::shared_ptr; - member_type member_; - pointer_type object_; - -public: - using result_type = R; - - weak_binder (member_type member, - Policy policy, pointer_type object) - : empty_base_optimization(std::move(policy)) - , member_(member) - , object_(object) - { } - - R operator()(Args... args) - { - if(auto p = object_.lock()) - return ((*p).*member_)(args...); - return this->member()(); - } -}; - -} // detail - -/** Returns a callback that can be used with std::bind and a weak_ptr. - When called, it tries to lock weak_ptr to get a shared_ptr. If successful, - it calls given member function with given arguments. If not successful, - the policy functor is called. Built-in policies are: - - ignore_if_invalid does nothing - throw_if_invalid throws `bad_weak_ptr` - return_default_if_invalid returns a chosen value - - Example: - - struct Foo { - void bar(int i) { - std::cout << i << std::endl; - } - }; - - struct do_something { - void operator()() { - std::cout << "outdated reference" << std::endl; - } - }; - - int main() - { - std::shared_ptr sp(new Foo()); - std::weak_ptr wp(sp); - - std::bind(weak_fn(&Foo::bar, wp), _1)(1); - sp.reset(); - std::bind(weak_fn(&Foo::bar, wp), 1)(); - std::bind(weak_fn(&Foo::bar, wp, do_something()), 1)(); - } -*/ -/** @{ */ -template -detail::weak_binder -weak_fn (R (T::*member)(Args...), std::shared_ptr p, - Policy policy) -{ - return detail::weak_binder(member, policy, p); -} - -template -detail::weak_binder, Args...> -weak_fn (R (T::*member)(Args...), std::shared_ptr p) -{ - return detail::weak_binder, Args...>(member, - default_invalid_policy{}, p); -} -/** @} */ - -} // beast - -#endif diff --git a/beast/win32_workaround.h b/beast/win32_workaround.h deleted file mode 100644 index 1739429052..0000000000 --- a/beast/win32_workaround.h +++ /dev/null @@ -1,45 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2015, 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_WINDOWS_H_INCLUDED -#define BEAST_WINDOWS_H_INCLUDED - -#ifdef _MSC_VER -#pragma push_macro("NOMINMAX") -#pragma push_macro("UNICODE") -#pragma push_macro("STRICT") -# ifndef NOMINMAX -# define NOMINMAX -# endif -# ifndef UNICODE -# define UNICODE -# endif -# ifndef STRICT -# define STRICT -# endif -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include -#pragma pop_macro("STRICT") -#pragma pop_macro("UNICODE") -#pragma pop_macro("NOMINMAX") - -#endif -#endif diff --git a/beast/xor_shift_engine.h b/beast/xor_shift_engine.h index bf773f0df9..5b917c5feb 100644 --- a/beast/xor_shift_engine.h +++ b/beast/xor_shift_engine.h @@ -20,7 +20,6 @@ #ifndef BEAST_RANDOM_XOR_SHIFT_ENGINE_H_INCLUDED #define BEAST_RANDOM_XOR_SHIFT_ENGINE_H_INCLUDED -#include #include #include #include @@ -48,14 +47,14 @@ public: operator()(); static - result_type BEAST_CONSTEXPR + result_type constexpr min() { return std::numeric_limits::min(); } static - result_type BEAST_CONSTEXPR + result_type constexpr max() { return std::numeric_limits::max(); diff --git a/tests.sh b/tests.sh deleted file mode 100755 index 8f50b3036e..0000000000 --- a/tests.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -# Runs all the tests in bin/ - -for f in bin/*.test -do -{ - echo -e "\033[94m$f\033[0m" - $f -} -done