diff --git a/Builds/VisualStudio2013/RippleD.vcxproj b/Builds/VisualStudio2013/RippleD.vcxproj index 64c135d19c..d79834d8c0 100644 --- a/Builds/VisualStudio2013/RippleD.vcxproj +++ b/Builds/VisualStudio2013/RippleD.vcxproj @@ -2590,6 +2590,9 @@ + + + diff --git a/Builds/VisualStudio2013/RippleD.vcxproj.filters b/Builds/VisualStudio2013/RippleD.vcxproj.filters index b2c9bd29d6..2748a1eaff 100644 --- a/Builds/VisualStudio2013/RippleD.vcxproj.filters +++ b/Builds/VisualStudio2013/RippleD.vcxproj.filters @@ -3048,6 +3048,15 @@ [1] Ripple\common + + [2] Old Ripple\ripple_core\functional + + + [2] Old Ripple\ripple_core\functional + + + [2] Old Ripple\ripple_core\functional + diff --git a/Builds/VisualStudio2013/ripple.sln b/Builds/VisualStudio2013/ripple.sln index 7eba733d5d..12114c44cd 100644 --- a/Builds/VisualStudio2013/ripple.sln +++ b/Builds/VisualStudio2013/ripple.sln @@ -1,6 +1,6 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 +# Visual Studio Express 2013 for Windows Desktop VisualStudioVersion = 12.0.30110.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "beast", "..\..\src\beast\Builds\VisualStudio2013\beast.vcxproj", "{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}" @@ -16,7 +16,6 @@ Global EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Debug|Win32.ActiveCfg = Debug|Win32 - {73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Debug|Win32.Build.0 = Debug|Win32 {73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Debug|x64.ActiveCfg = Debug|x64 {73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Debug|x64.Build.0 = Debug|x64 {73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Release|Win32.ActiveCfg = Release|Win32 diff --git a/doc/todo/VFALCO_TODO.txt b/doc/todo/VFALCO_TODO.txt index 4f11a6f5c2..16dffd223d 100644 --- a/doc/todo/VFALCO_TODO.txt +++ b/doc/todo/VFALCO_TODO.txt @@ -53,19 +53,6 @@ David Features: down the cache and then something that uses the cache, objects may get put in the cache after it was shut down. -- Do something about the throw() reporting weaknesses: - * Make sure all Sconstruct and .pro builds have debug symbols in release - * Replace all throw with beast::Throw() - (Only in ripple sources, not in Subtrees/, protobuf, or websocket) - - Improved Beast exception object, provides __FILE__ and __LINE__ - - Add file and line capabilities to beast::Throw() - - Allow beast::Throw to be hooked for logging - - Add stack trace capability to beast::Throw() diagnostics via the hook - (use the existing beast::SystemStats::getStackBacktrace()) - - Implement getStackBacktrace for BEAST_BSD targets - - Add UnhandledExceptionCatcher to beast - - Return EXIT_FAILURE on unhandled exception - - Consolidate JSON code maybe use Beast - Deeply create directories specified in config settings @@ -132,20 +119,10 @@ David Features: - Rename LedgerMaster to Ledgers, create ILedgers interface. -- Replace all NULL with nullptr - -- Make TxFormats a member of ICore instead of a singleton. - PROBLEM: STObject derived classes like STInt16 make direct use of the - singleton. It might have to remain a singleton. At the very least, - it should be a SharedSingleton to resolve ordering issues. - - Replace C11X with BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS - Remove "ENABLE_INSECURE" when the time is right. -- lift unique_ptr / auto_ptr into ripple namespace, - or replace with ScopedPointer (preferred) - - Go searching through VFALCO notes and fix everything - Deal with function-level statics used for SqliteDatabase (like in diff --git a/src/beast/Builds/VisualStudio2013/beast.vcxproj b/src/beast/Builds/VisualStudio2013/beast.vcxproj index ee0ff1d65f..84262d0984 100644 --- a/src/beast/Builds/VisualStudio2013/beast.vcxproj +++ b/src/beast/Builds/VisualStudio2013/beast.vcxproj @@ -47,12 +47,6 @@ true true - - true - true - true - true - true true @@ -142,7 +136,6 @@ - @@ -299,7 +292,6 @@ - @@ -340,26 +332,16 @@ - - - - - - - - - - @@ -988,12 +970,6 @@ true true - - true - true - true - true - true true @@ -1012,12 +988,6 @@ true true - - true - true - true - true - true true @@ -1036,12 +1006,6 @@ true true - - true - true - true - true - true true @@ -1114,18 +1078,6 @@ true true - - true - true - true - true - - - true - true - true - true - true true @@ -1138,12 +1090,6 @@ true true - - true - true - true - true - true true @@ -1156,18 +1102,6 @@ true true - - true - true - true - true - - - true - true - true - true - true diff --git a/src/beast/Builds/VisualStudio2013/beast.vcxproj.filters b/src/beast/Builds/VisualStudio2013/beast.vcxproj.filters index eccb9d4e45..91a7c34707 100644 --- a/src/beast/Builds/VisualStudio2013/beast.vcxproj.filters +++ b/src/beast/Builds/VisualStudio2013/beast.vcxproj.filters @@ -4,9 +4,6 @@ beast_core\native - - beast_core\native - beast_core\native @@ -111,9 +108,6 @@ {d3ea4af5-ae48-4144-a2ef-a212342d72ee} - - {a1a38659-7779-41d6-8a3c-068433c4deaf} - {69e28551-92ea-420b-a465-75ed248e3b59} @@ -159,9 +153,6 @@ {1b2e8962-c087-4453-8107-7077c2de5846} - - {91538dcf-b219-4c80-9861-bb4949089775} - {c0724499-ab69-40c3-90e2-65242dbd2eaa} @@ -326,9 +317,6 @@ beast_core\containers - - beast_core\containers - beast_core\containers @@ -401,21 +389,12 @@ beast_core\text - - beast_core\threads - beast_core\threads beast_core\threads - - beast_core\threads - - - beast_core\threads - beast_core\threads @@ -425,12 +404,6 @@ beast_core\time - - beast_core\xml - - - beast_core\xml - beast_core\diagnostic @@ -521,24 +494,9 @@ beast_core\thread - - beast_core\thread - - - beast_core\thread\detail - beast_core\thread\detail - - beast_core\thread\impl - - - beast_core\thread\impl - - - beast_core\thread\impl - beast_core\thread @@ -677,9 +635,6 @@ beast - - beast - beast\utility @@ -1265,9 +1220,6 @@ beast_core\native - - beast_core\native - beast_core\native @@ -1277,9 +1229,6 @@ beast_core\native - - beast_core\native - beast_core\native @@ -1307,30 +1256,15 @@ beast_core\text - - beast_core\threads - - - beast_core\threads - beast_core\time - - beast_core\xml - - - beast_core\xml - beast_core\native beast_core\native - - beast_core\native - beast_core\native @@ -1391,9 +1325,6 @@ beast_core\diagnostic - - beast_core\thread\impl - beast_core\thread diff --git a/src/beast/CodingStyle.md b/src/beast/CodingStyle.md index 92b35da4ef..bd598c3b51 100644 --- a/src/beast/CodingStyle.md +++ b/src/beast/CodingStyle.md @@ -120,7 +120,7 @@ overlooked. Blank lines are used to separate code into "paragraphs." `static_cast`. And when you're reinterpreting data, always use `reinterpret_cast`. * Until C++ gets a universal 64-bit primitive type (part of the C++11 - standard), it's best to stick to the `int64` and `uint64` typedefs. + standard), it's best to stick to the `std::int64_t` and `std::uint64_t` typedefs. ## Object lifetime and ownership diff --git a/src/beast/TODO.txt b/src/beast/TODO.txt index b58e7f661c..5ea09353ae 100644 --- a/src/beast/TODO.txt +++ b/src/beast/TODO.txt @@ -2,12 +2,12 @@ BEAST TODO -------------------------------------------------------------------------------- +- Change sqdb to use exceptions instead of errors + - Use SemanticVersion for beast version numbers to replace BEAST_VERSION - add support for a __PRETTY_FUNCTION__ equivalent for all environments -- add expectThrow() to UnitTest, where it expects an exception - - Import secp256k1 from sipa - Set sqlite thread safety model to '2' in beast_sqlite @@ -18,8 +18,6 @@ BEAST TODO - Rename HeapBlock routines to not conflict with _CRTDBG_MAP_ALLOC macros -- Design a WeakPtr / SharedPtr / SharedObject intrusive system - - Implement beast::Bimap? - Use Bimap for storage in the DeadlineTimer::Manager, to support @@ -28,39 +26,18 @@ BEAST TODO - Think about adding a shouldStop bool to InterruptibleThread, along with a shouldStop () function returning bool, and a stop() method. -- Make OwnedArray add routines return a pointer instead of reference - - Tidy up CacheLine, MemoryAlignment -- Remove anything having to do with DLL builds like - BEAST_DLL, BEAST_DLL_BUILD, BEAST_DISABLE_DLL_ALLOCATORS - -- Fix FifoFreeStoreWithTLS reference counting bug - - Implement a reasonable substitute for boost's thread_local_storage -- Think about doing away with BEAST_CALLTYPE and BEAST_API - - Rename malloc/calloc JUCE members that conflict with the debug CRT from MSVC - Reformat every Doxygen comment - Fix Doxygen metatags - update Beast Doxyfile -- Rename include guards to boost style, e.g. BEAST_THROW_H_INCLUDED - -- Clean up CacheLine, StaticObject - -- Clean up ConcurrentObject - - Rename SharedData to SharedState or something? -- Put BEAST_PUBLIC_FUNCTION in front of all loose functions - -- restructure the repo sources to look like this: - /Source/beast/beast_core/beast_core.h - etc... - - Make sure the template BeastConfig.h is included in the Doxyfile - Implement robust key/value database with bulk write diff --git a/src/beast/beast/Arithmetic.h b/src/beast/beast/Arithmetic.h index da2925030e..bcbadc43dd 100644 --- a/src/beast/beast/Arithmetic.h +++ b/src/beast/beast/Arithmetic.h @@ -25,11 +25,11 @@ #define BEAST_ARITHMETIC_H_INCLUDED #include "Config.h" -#include "CStdInt.h" #include "utility/noexcept.h" #include +#include #include namespace beast { @@ -197,12 +197,6 @@ inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperL } //============================================================================== -/** Handy function to swap two values. */ -template -inline void swapVariables (Type& variable1, Type& variable2) -{ - std::swap (variable1, variable2); -} /** Handy function for getting the number of elements in a simple const C array. E.g. @@ -220,54 +214,12 @@ int numElementsInArray (Type (&array)[N]) return N; } -//============================================================================== -// Some useful maths functions that aren't always present with all compilers and build settings. - -/** Using beast_hypot is easier than dealing with the different types of hypot function - that are provided by the various platforms and compilers. */ -template -inline Type beast_hypot (Type a, Type b) noexcept -{ - #if BEAST_MSVC - return static_cast (_hypot (a, b)); - #else - return static_cast (hypot (a, b)); - #endif -} - /** 64-bit abs function. */ -inline int64 abs64 (const int64 n) noexcept +inline std::int64_t abs64 (const std::int64_t n) noexcept { return (n >= 0) ? n : -n; } -//============================================================================== -/** A predefined value for Pi, at double-precision. - @see float_Pi -*/ -const double double_Pi = 3.1415926535897932384626433832795; - -/** A predefined value for Pi, at single-precision. - @see double_Pi -*/ -const float float_Pi = 3.14159265358979323846f; - - -//============================================================================== -/** The isfinite() method seems to vary between platforms, so this is a - platform-independent function for it. -*/ -template -inline bool beast_isfinite (FloatingPointType value) -{ - #if BEAST_WINDOWS - return _finite (value); - #elif BEAST_ANDROID - return isfinite (value); - #else - return std::isfinite (value); - #endif -} //============================================================================== #if BEAST_MSVC @@ -311,149 +263,6 @@ inline int roundToInt (const FloatType value) noexcept #pragma optimize ("", on) // resets optimisations to the project defaults #endif -/** Fast floating-point-to-integer conversion. - - This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works - fine for values above zero, but negative numbers are rounded the wrong way. -*/ -inline int roundToIntAccurate (const double value) noexcept -{ - #ifdef __INTEL_COMPILER - #pragma float_control (pop) - #endif - - return roundToInt (value + 1.5e-8); -} - -/** Fast floating-point-to-integer conversion. - - This is faster than using the normal c++ cast to convert a double to an int, and - it will round the value to the nearest integer, rather than rounding it down - like the normal cast does. - - Note that this routine gets its speed at the expense of some accuracy, and when - rounding values whose floating point component is exactly 0.5, odd numbers and - even numbers will be rounded up or down differently. For a more accurate conversion, - see roundDoubleToIntAccurate(). -*/ -inline int roundDoubleToInt (const double value) noexcept -{ - return roundToInt (value); -} - -/** Fast floating-point-to-integer conversion. - - This is faster than using the normal c++ cast to convert a float to an int, and - it will round the value to the nearest integer, rather than rounding it down - like the normal cast does. - - Note that this routine gets its speed at the expense of some accuracy, and when - rounding values whose floating point component is exactly 0.5, odd numbers and - even numbers will be rounded up or down differently. -*/ -inline int roundFloatToInt (const float value) noexcept -{ - return roundToInt (value); -} - -//============================================================================== -/** Returns true if the specified integer is a power-of-two. -*/ -template -bool isPowerOfTwo (IntegerType value) -{ - return (value & (value - 1)) == 0; -} - -/** Returns the smallest power-of-two which is equal to or greater than the given integer. -*/ -inline int nextPowerOfTwo (int n) noexcept -{ - --n; - n |= (n >> 1); - n |= (n >> 2); - n |= (n >> 4); - n |= (n >> 8); - n |= (n >> 16); - return n + 1; -} - -/** Performs a modulo operation, but can cope with the dividend being negative. - The divisor must be greater than zero. -*/ -template -IntegerType negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept -{ - bassert (divisor > 0); - dividend %= divisor; - return (dividend < 0) ? (dividend + divisor) : dividend; -} - -//============================================================================== -#if (BEAST_INTEL && BEAST_32BIT) || defined (DOXYGEN) - /** This macro can be applied to a float variable to check whether it contains a denormalised - value, and to normalise it if necessary. - On CPUs that aren't vulnerable to denormalisation problems, this will have no effect. - */ - #define BEAST_UNDENORMALISE(x) x += 1.0f; x -= 1.0f; -#else - #define BEAST_UNDENORMALISE(x) -#endif - -//============================================================================== -/** This namespace contains a few template classes for helping work out class type variations. -*/ -namespace TypeHelpers -{ - #if BEAST_VC8_OR_EARLIER - #define PARAMETER_TYPE(type) const type& - #else - /** The ParameterType struct is used to find the best type to use when passing some kind - of object as a parameter. - - Of course, this is only likely to be useful in certain esoteric template situations. - - Because "typename TypeHelpers::ParameterType::type" is a bit of a mouthful, there's - a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect. - - E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))" - would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as - pass-by-value, but passing objects as a const reference, to avoid copying. - */ - template struct ParameterType { typedef const Type& type; }; - - #if ! DOXYGEN - template struct ParameterType { typedef Type& type; }; - template struct ParameterType { typedef Type* type; }; - template <> struct ParameterType { typedef char type; }; - template <> struct ParameterType { typedef unsigned char type; }; - template <> struct ParameterType { typedef short type; }; - template <> struct ParameterType { typedef unsigned short type; }; - template <> struct ParameterType { typedef int type; }; - template <> struct ParameterType { typedef unsigned int type; }; - template <> struct ParameterType { typedef long type; }; - template <> struct ParameterType { typedef unsigned long type; }; - template <> struct ParameterType { typedef int64 type; }; - template <> struct ParameterType { typedef uint64 type; }; - template <> struct ParameterType { typedef bool type; }; - template <> struct ParameterType { typedef float type; }; - template <> struct ParameterType { typedef double type; }; - #endif - - /** A helpful macro to simplify the use of the ParameterType template. - @see ParameterType - */ - #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType::type - #endif - - - /** These templates are designed to take a type, and if it's a double, they return a double - type; for anything else, they return a float type. - */ - template struct SmallestFloatType { typedef float type; }; - template <> struct SmallestFloatType { typedef double type; }; -} - } #endif diff --git a/src/beast/beast/Atomic.h b/src/beast/beast/Atomic.h index bd252f70b3..ffeb82a695 100644 --- a/src/beast/beast/Atomic.h +++ b/src/beast/beast/Atomic.h @@ -25,11 +25,12 @@ #define BEAST_ATOMIC_H_INCLUDED #include "Config.h" -#include "CStdInt.h" #include "StaticAssert.h" #include "utility/noexcept.h" +#include + namespace beast { //============================================================================== @@ -158,10 +159,10 @@ private: template static inline Dest castTo (Source value) noexcept { union { Dest d; Source s; } u; u.s = value; return u.d; } - static inline Type castFrom32Bit (int32 value) noexcept { return castTo (value); } - static inline Type castFrom64Bit (int64 value) noexcept { return castTo (value); } - static inline int32 castTo32Bit (Type value) noexcept { return castTo (value); } - static inline int64 castTo64Bit (Type value) noexcept { return castTo (value); } + static inline Type castFrom32Bit (std::int32_t value) noexcept { return castTo (value); } + static inline Type castFrom64Bit (std::int64_t value) noexcept { return castTo (value); } + static inline std::int32_t castTo32Bit (Type value) noexcept { return castTo (value); } + static inline std::int64_t castTo64Bit (Type value) noexcept { return castTo (value); } Type operator++ (int); // better to just use pre-increment with atomics.. @@ -174,14 +175,14 @@ private: return sizeof (ValueType) == 1 ? (ValueType) -(signed char) n : (sizeof (ValueType) == 2 ? (ValueType) -(short) n : (sizeof (ValueType) == 4 ? (ValueType) -(int) n - : ((ValueType) -(int64) n))); + : ((ValueType) -(std::int64_t) n))); } /** This templated negate function will negate pointers as well as integers */ template inline PointerType* negateValue (PointerType* n) noexcept { - return reinterpret_cast (-reinterpret_cast (n)); + return reinterpret_cast (-reinterpret_cast (n)); } }; @@ -274,14 +275,14 @@ template inline Type Atomic::get() const noexcept { #if BEAST_ATOMICS_MAC - return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (BEAST_MAC_ATOMICS_VOLATILE int32_t*) &value)) - : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (BEAST_MAC_ATOMICS_VOLATILE int64_t*) &value)); + return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) OSAtomicAdd32Barrier ((int32_t) 0, (BEAST_MAC_ATOMICS_VOLATILE int32_t*) &value)) + : castFrom64Bit ((std::int64_t) OSAtomicAdd64Barrier ((int64_t) 0, (BEAST_MAC_ATOMICS_VOLATILE int64_t*) &value)); #elif BEAST_ATOMICS_WINDOWS - return sizeof (Type) == 4 ? castFrom32Bit ((int32) beast_InterlockedExchangeAdd ((volatile long*) &value, (long) 0)) - : castFrom64Bit ((int64) beast_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0)); + return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) beast_InterlockedExchangeAdd ((volatile long*) &value, (long) 0)) + : castFrom64Bit ((std::int64_t) beast_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0)); #elif BEAST_ATOMICS_GCC - return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0)) - : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0)); + return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) __sync_add_and_fetch ((volatile std::int32_t*) &value, 0)) + : castFrom64Bit ((std::int64_t) __sync_add_and_fetch ((volatile std::int64_t*) &value, 0)); #endif } @@ -293,8 +294,8 @@ inline Type Atomic::exchange (const Type newValue) noexcept while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; } return currentVal; #elif BEAST_ATOMICS_WINDOWS - return sizeof (Type) == 4 ? castFrom32Bit ((int32) beast_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue))) - : castFrom64Bit ((int64) beast_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue))); + return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) beast_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue))) + : castFrom64Bit ((std::int64_t) beast_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue))); #endif } @@ -379,8 +380,8 @@ inline bool Atomic::compareAndSetBool (const Type newValue, const Type val #elif BEAST_ATOMICS_WINDOWS return compareAndSetValue (newValue, valueToCompare) == valueToCompare; #elif BEAST_ATOMICS_GCC - return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)) - : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)); + return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile std::int32_t*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)) + : __sync_bool_compare_and_swap ((volatile std::int64_t*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)); #endif } @@ -399,11 +400,11 @@ inline Type Atomic::compareAndSetValue (const Type newValue, const Type va } #elif BEAST_ATOMICS_WINDOWS - return sizeof (Type) == 4 ? castFrom32Bit ((int32) beast_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare))) - : castFrom64Bit ((int64) beast_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare))); + return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) beast_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare))) + : castFrom64Bit ((std::int64_t) beast_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare))); #elif BEAST_ATOMICS_GCC - return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))) - : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue))); + return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) __sync_val_compare_and_swap ((volatile std::int32_t*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))) + : castFrom64Bit ((std::int64_t) __sync_val_compare_and_swap ((volatile std::int64_t*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue))); #endif } diff --git a/src/beast/beast/ByteOrder.h b/src/beast/beast/ByteOrder.h index 0e40616e7d..e17736d348 100644 --- a/src/beast/beast/ByteOrder.h +++ b/src/beast/beast/ByteOrder.h @@ -25,9 +25,10 @@ #define BEAST_BYTEORDER_H_INCLUDED #include "Config.h" -#include "CStdInt.h" #include "Uncopyable.h" +#include + namespace beast { //============================================================================== @@ -39,51 +40,51 @@ class ByteOrder : public Uncopyable public: //============================================================================== /** Swaps the upper and lower bytes of a 16-bit integer. */ - static uint16 swap (uint16 value); + static std::uint16_t swap (std::uint16_t value); /** Reverses the order of the 4 bytes in a 32-bit integer. */ - static uint32 swap (uint32 value); + static std::uint32_t swap (std::uint32_t value); /** Reverses the order of the 8 bytes in a 64-bit integer. */ - static uint64 swap (uint64 value); + 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 uint16 swapIfBigEndian (uint16 value); + 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 uint32 swapIfBigEndian (uint32 value); + 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 uint64 swapIfBigEndian (uint64 value); + 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 uint16 swapIfLittleEndian (uint16 value); + 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 uint32 swapIfLittleEndian (uint32 value); + 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 uint64 swapIfLittleEndian (uint64 value); + static std::uint64_t swapIfLittleEndian (std::uint64_t value); //============================================================================== /** Turns 2 bytes into a little-endian integer. */ - static uint16 littleEndianShort (const void* bytes); + static std::uint16_t littleEndianShort (const void* bytes); /** Turns 4 bytes into a little-endian integer. */ - static uint32 littleEndianInt (const void* bytes); + static std::uint32_t littleEndianInt (const void* bytes); /** Turns 4 bytes into a little-endian integer. */ - static uint64 littleEndianInt64 (const void* bytes); + static std::uint64_t littleEndianInt64 (const void* bytes); /** Turns 2 bytes into a big-endian integer. */ - static uint16 bigEndianShort (const void* bytes); + static std::uint16_t bigEndianShort (const void* bytes); /** Turns 4 bytes into a big-endian integer. */ - static uint32 bigEndianInt (const void* bytes); + static std::uint32_t bigEndianInt (const void* bytes); /** Turns 4 bytes into a big-endian integer. */ - static uint64 bigEndianInt64 (const void* bytes); + 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). */ @@ -111,16 +112,16 @@ private: #pragma intrinsic (_byteswap_ulong) #endif -inline uint16 ByteOrder::swap (uint16 n) +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)); + return static_cast (_byteswap_ushort (n)); #else - return static_cast ((n << 8) | (n >> 8)); + return static_cast ((n << 8) | (n >> 8)); #endif } -inline uint32 ByteOrder::swap (uint32 n) +inline std::uint32_t ByteOrder::swap (std::uint32_t n) { #if BEAST_MAC || BEAST_IOS return OSSwapInt32 (n); @@ -143,48 +144,48 @@ inline uint32 ByteOrder::swap (uint32 n) #endif } -inline uint64 ByteOrder::swap (uint64 value) +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 (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32)); + return (((std::int64_t) swap ((std::uint32_t) value)) << 32) | swap ((std::uint32_t) (value >> 32)); #endif } #if BEAST_LITTLE_ENDIAN - inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; } - inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; } - inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; } - inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); } - inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); } - inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); } - inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast (bytes); } - inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast (bytes); } - inline uint64 ByteOrder::littleEndianInt64 (const void* const bytes) { return *static_cast (bytes); } - inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast (bytes)); } - inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast (bytes)); } - inline uint64 ByteOrder::bigEndianInt64 (const void* const bytes) { return swap (*static_cast (bytes)); } + 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 uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); } - inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); } - inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); } - inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; } - inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; } - inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; } - inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast (bytes)); } - inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast (bytes)); } - inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast (bytes); } - inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast (bytes); } - inline uint64 ByteOrder::bigEndianInt64 (const void* const bytes) { return *static_cast (bytes); } + 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) (uint8) bytes[1]) << 8) | ((int) (uint8) bytes[0]); } -inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((int) (uint8) bytes[1]) << 8) | ((int) (uint8) bytes[2]); } +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); } @@ -211,29 +212,29 @@ struct SwapBytes // Specializations for signed integers template <> -struct SwapBytes +struct SwapBytes { - inline int16 operator() (int16 value) const noexcept + inline std::int16_t operator() (std::int16_t value) const noexcept { - return static_cast (ByteOrder::swap (static_cast (value))); + return static_cast (ByteOrder::swap (static_cast (value))); } }; template <> -struct SwapBytes +struct SwapBytes { - inline int32 operator() (int32 value) const noexcept + inline std::int32_t operator() (std::int32_t value) const noexcept { - return static_cast (ByteOrder::swap (static_cast (value))); + return static_cast (ByteOrder::swap (static_cast (value))); } }; template <> -struct SwapBytes +struct SwapBytes { - inline int64 operator() (int64 value) const noexcept + inline std::int64_t operator() (std::int64_t value) const noexcept { - return static_cast (ByteOrder::swap (static_cast (value))); + return static_cast (ByteOrder::swap (static_cast (value))); } }; diff --git a/src/beast/beast/CStdInt.h b/src/beast/beast/CStdInt.h deleted file mode 100644 index 265f3d9f19..0000000000 --- a/src/beast/beast/CStdInt.h +++ /dev/null @@ -1,88 +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_CSTDINT_H_INCLUDED -#define BEAST_CSTDINT_H_INCLUDED - -#include "Config.h" - -namespace beast { - -typedef signed char int8; -typedef signed short int16; -typedef signed int int32; -typedef unsigned char uint8; -typedef unsigned short uint16; -typedef unsigned int uint32; - -#if BEAST_MSVC - typedef __int64 int64; - typedef unsigned __int64 uint64; - - /** A platform-independent macro for writing 64-bit literals, needed because - different compilers have different syntaxes for this. - - E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for - GCC, or 0x1000000000 for MSVC. - */ - #define literal64bit(longLiteral) ((__int64) longLiteral) - -#else - /** A platform-independent 64-bit integer type. */ - typedef long long int64; - /** A platform-independent 64-bit unsigned integer type. */ - typedef unsigned long long uint64; - /** A platform-independent macro for writing 64-bit literals, needed because - different compilers have different syntaxes for this. - - E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for - GCC, or 0x1000000000 for MSVC. - */ - #define literal64bit(longLiteral) (longLiteral##LL) - -#endif - -#if BEAST_64BIT - /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */ - typedef int64 pointer_sized_int; - /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */ - typedef uint64 pointer_sized_uint; -#elif BEAST_MSVC - /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */ - typedef _W64 int pointer_sized_int; - /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */ - typedef _W64 unsigned int pointer_sized_uint; -#else - /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */ - typedef int pointer_sized_int; - /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */ - typedef unsigned int pointer_sized_uint; -#endif - -#if BEAST_MSVC - typedef pointer_sized_int ssize_t; -#endif - -} - -#endif diff --git a/src/beast/beast/HeapBlock.h b/src/beast/beast/HeapBlock.h index 875dae0e47..aff4006e62 100644 --- a/src/beast/beast/HeapBlock.h +++ b/src/beast/beast/HeapBlock.h @@ -119,7 +119,7 @@ namespace HeapBlockHelper 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, OwnedArray, MemoryBlock + @see Array, MemoryBlock */ template class HeapBlock : public Uncopyable @@ -339,10 +339,6 @@ private: { HeapBlockHelper::ThrowOnFail::check (data); } - - #if ! (defined (BEAST_DLL) || defined (BEAST_DLL_BUILD)) - BEAST_PREVENT_HEAP_ALLOCATION // Creating a 'new HeapBlock' would be missing the point! - #endif }; } diff --git a/src/beast/beast/Memory.h b/src/beast/beast/Memory.h index a95627542a..adb3717f2e 100644 --- a/src/beast/beast/Memory.h +++ b/src/beast/beast/Memory.h @@ -78,7 +78,7 @@ Type* createCopyIfNotNull (const Type* pointer) /** 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 BEAST_API ScopedAutoReleasePool : public Uncopyable + class ScopedAutoReleasePool : public Uncopyable { public: ScopedAutoReleasePool(); diff --git a/src/beast/beast/asio/impl/IPAddressConversion.cpp b/src/beast/beast/asio/impl/IPAddressConversion.cpp index 62511b6f64..d97f3811f4 100644 --- a/src/beast/beast/asio/impl/IPAddressConversion.cpp +++ b/src/beast/beast/asio/impl/IPAddressConversion.cpp @@ -33,7 +33,7 @@ Endpoint from_asio (boost::asio::ip::address const& address) } // VFALCO TODO IPv6 support - bassertfalse; + assert(false); return Endpoint(); } @@ -52,7 +52,7 @@ boost::asio::ip::address to_asio_address (Endpoint const& endpoint) } // VFALCO TODO IPv6 support - bassertfalse; + assert(false); return boost::asio::ip::address ( boost::asio::ip::address_v6 ()); } diff --git a/src/beast/beast/chrono/RelativeTime.h b/src/beast/beast/chrono/RelativeTime.h index 57da666b5b..b4e849f0bb 100644 --- a/src/beast/beast/chrono/RelativeTime.h +++ b/src/beast/beast/chrono/RelativeTime.h @@ -41,7 +41,7 @@ namespace beast { If you need an absolute time, (i.e. a date + time), see the Time class. */ -class BEAST_API RelativeTime +class RelativeTime { public: //============================================================================== @@ -88,7 +88,7 @@ public: /** Creates a new RelativeTime object representing a number of milliseconds. @see seconds, minutes, hours, days, weeks */ - static RelativeTime milliseconds (int64 milliseconds) noexcept; + static RelativeTime milliseconds (std::int64_t milliseconds) noexcept; /** Creates a new RelativeTime object representing a number of seconds. @see milliseconds, minutes, hours, days, weeks @@ -119,7 +119,7 @@ public: /** Returns the number of milliseconds this time represents. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks */ - int64 inMilliseconds() const noexcept; + std::int64_t inMilliseconds() const noexcept; /** Returns the number of seconds this time represents. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks diff --git a/src/beast/beast/chrono/impl/RelativeTime.cpp b/src/beast/beast/chrono/impl/RelativeTime.cpp index 8a79c7fd20..853940bb3e 100644 --- a/src/beast/beast/chrono/impl/RelativeTime.cpp +++ b/src/beast/beast/chrono/impl/RelativeTime.cpp @@ -54,7 +54,7 @@ RelativeTime RelativeTime::milliseconds (const int milliseconds) noexcept return RelativeTime (milliseconds * 0.001); } -RelativeTime RelativeTime::milliseconds (const int64 milliseconds) noexcept +RelativeTime RelativeTime::milliseconds (const std::int64_t milliseconds) noexcept { return RelativeTime (milliseconds * 0.001); } @@ -86,9 +86,9 @@ RelativeTime RelativeTime::weeks (const RelativeTime::value_type numberOfWeeks) //============================================================================== -int64 RelativeTime::inMilliseconds() const noexcept +std::int64_t RelativeTime::inMilliseconds() const noexcept { - return (int64) (numSeconds * 1000.0); + return (std::int64_t) (numSeconds * 1000.0); } RelativeTime::value_type RelativeTime::inMinutes() const noexcept @@ -301,7 +301,7 @@ static double monotonicCurrentTimeInSeconds() { numerator = timebase.numer; // VFALCO NOTE I don't understand this code - //denominator = timebase.denom * (uint64) 1000000 * 1000.0; + //denominator = timebase.denom * (std::uint64_t) 1000000 * 1000.0; denominator = timebase.denom * 1000000000.0; } diff --git a/src/beast/beast/config/CompilerConfig.h b/src/beast/beast/config/CompilerConfig.h index 534588f7c3..7cdaf733a3 100644 --- a/src/beast/beast/config/CompilerConfig.h +++ b/src/beast/beast/config/CompilerConfig.h @@ -42,10 +42,8 @@ /** This macro defines the C calling convention used as the standard for Beast calls. */ #if BEAST_MSVC -# define BEAST_CALLTYPE __stdcall # define BEAST_CDECL __cdecl #else -# define BEAST_CALLTYPE # define BEAST_CDECL #endif @@ -148,16 +146,6 @@ extern void beast_reportFatalError (char const* message, char const* fileName, i //------------------------------------------------------------------------------ -/** This macro can be added to class definitions to disable the use of new/delete to - allocate the object on the heap, forcing it to only be used as a stack or member variable. -*/ -#define BEAST_PREVENT_HEAP_ALLOCATION \ - private: \ - static void* operator new (size_t); \ - static void operator delete (void*); - -//------------------------------------------------------------------------------ - #if ! DOXYGEN #define BEAST_JOIN_MACRO_HELPER(a, b) a ## b #define BEAST_STRINGIFY_MACRO_HELPER(a) #a @@ -175,19 +163,6 @@ extern void beast_reportFatalError (char const* message, char const* fileName, i //------------------------------------------------------------------------------ -#if BEAST_DEBUG || DOXYGEN -/** A platform-independent way of forcing an inline function. - Use the syntax: @code - forcedinline void myfunction (int x) - @endcode -*/ -# define forcedinline inline -#elif BEAST_MSVC -# define forcedinline __forceinline -#else -# define forcedinline inline __attribute__((always_inline)) -#endif - #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. diff --git a/src/beast/beast/config/ContractChecks.h b/src/beast/beast/config/ContractChecks.h index 59cad4231c..d611d5f036 100644 --- a/src/beast/beast/config/ContractChecks.h +++ b/src/beast/beast/config/ContractChecks.h @@ -24,13 +24,10 @@ #if defined (fatal_error) || \ defined (fatal_condition) || \ - defined (fatal_assert) || \ defined (meets_condition) || \ defined (meets_precondition) || \ defined (meets_postcondition) || \ defined (meets_invariant) || \ - defined (check_precondition) || \ - defined (check_postcondition) || \ defined (check_invariant) #error "Programming by contract macros cannot be overriden!" #endif @@ -52,13 +49,6 @@ (((!!(condition)) || (beast_reportFatalError ( \ category " '" BEAST_STRINGIFY(condition) "' failed.", __FILE__, __LINE__), 0))) -/** Replacement for assert which generates a fatal error if the condition is false. - The condition is always evaluated regardless of compilation settings. - Meets this declaration syntax: - @code inline void fatal_assert (bool condition); @endcode -*/ -#define fatal_assert(condition) fatal_condition(condition,"Assertion") - /** Reports a fatal error message type if the condition is false The condition is always evaluated regardless of settings. Meets this declaration syntax: @@ -87,12 +77,8 @@ */ /** @{ */ #if ! BEAST_DISABLE_CONTRACT_CHECKS -# define check_precondition(condition) meets_precondition(condition) -# define check_postcondition(condition) meets_postcondition(condition) # define check_invariant(condition) meets_invariant(condition) #else -# define check_precondition(condition) ((void)0) -# define check_postcondition(condition) ((void)0) # define check_invariant(condition) ((void)0) #endif /** @} */ diff --git a/src/beast/beast/config/StandardConfig.h b/src/beast/beast/config/StandardConfig.h index 6f2a67c875..f620563c4a 100644 --- a/src/beast/beast/config/StandardConfig.h +++ b/src/beast/beast/config/StandardConfig.h @@ -74,40 +74,4 @@ #undef max #undef min -//------------------------------------------------------------------------------ - -// DLL building settings on Windows -// -// VFALCO TODO Deprecate this -// -#if BEAST_MSVC - #ifdef BEAST_DLL_BUILD - #define BEAST_API __declspec (dllexport) - #pragma warning (disable: 4251) - #elif defined (BEAST_DLL) - #define BEAST_API __declspec (dllimport) - #pragma warning (disable: 4251) - #endif - #ifdef __INTEL_COMPILER - #pragma warning (disable: 1125) // (virtual override warning) - #endif -#elif defined (BEAST_DLL) || defined (BEAST_DLL_BUILD) - #define BEAST_API __attribute__ ((visibility("default"))) -#endif - -//------------------------------------------------------------------------------ - -#ifndef BEAST_API -#define BEAST_API /**< This macro is added to all beast public class declarations. */ -#endif - -#if BEAST_MSVC && BEAST_DLL_BUILD -#define BEAST_PUBLIC_IN_DLL_BUILD(decl) public: decl; private: -#else -#define BEAST_PUBLIC_IN_DLL_BUILD(decl) decl; -#endif - -/** This macro is added to all beast public function declarations. */ -#define BEAST_PUBLIC_FUNCTION BEAST_API BEAST_CALLTYPE - #endif diff --git a/src/beast/beast/crypto/MurmurHash.h b/src/beast/beast/crypto/MurmurHash.h index 724d62d2fe..a9bda5c1ca 100644 --- a/src/beast/beast/crypto/MurmurHash.h +++ b/src/beast/beast/crypto/MurmurHash.h @@ -20,22 +20,23 @@ #ifndef BEAST_CRYPTO_MURMURHASH_H_INCLUDED #define BEAST_CRYPTO_MURMURHASH_H_INCLUDED -#include "../CStdInt.h" +#include +#include // Original source code links in .cpp file namespace beast { namespace Murmur { -extern void MurmurHash3_x86_32 (const void* key, int len, uint32 seed, void* out); -extern void MurmurHash3_x86_128 (const void* key, int len, uint32 seed, void* out); -extern void MurmurHash3_x64_128 (const void* key, int len, uint32 seed, void* out); +extern void MurmurHash3_x86_32 (const void* key, int len, std::uint32_t seed, void* out); +extern void MurmurHash3_x86_128 (const void* key, int len, std::uint32_t seed, void* out); +extern void MurmurHash3_x64_128 (const void* key, int len, std::uint32_t seed, void* out); // Uses Beast to choose an appropriate routine // This handy template deduces which size hash is desired template -inline void Hash (const void* key, int len, uint32 seed, HashType* out) +inline void Hash (const void* key, int len, std::uint32_t seed, HashType* out) { switch (8 * sizeof (HashType)) { @@ -72,7 +73,7 @@ inline void Hash (const void* key, int len, uint32 seed, HashType* out) #endif default: - Throw (std::runtime_error ("invalid key size in MurmurHash")); + throw std::runtime_error ("invalid key size in MurmurHash"); break; }; } diff --git a/src/beast/beast/crypto/Sha256.h b/src/beast/beast/crypto/Sha256.h index 9f3c0d3e0f..c415ac0675 100644 --- a/src/beast/beast/crypto/Sha256.h +++ b/src/beast/beast/crypto/Sha256.h @@ -21,9 +21,9 @@ #define BEAST_CRYPTO_SHA256_H_INCLUDED #include "../Config.h" -#include "../CStdInt.h" #include +#include //------------------------------------------------------------------------------ @@ -37,14 +37,14 @@ enum }; /** A container suitable for holding the resulting hash. */ -typedef std::array digest_type; +typedef std::array digest_type; namespace detail { struct Context { - beast::uint32 state[8]; - beast::uint64 bitcount; - beast::uint8 buffer[Sha256::blockLength]; + std::uint32_t state[8]; + std::uint64_t bitcount; + std::uint8_t buffer[Sha256::blockLength]; }; } @@ -59,12 +59,12 @@ public: /** @{ */ void update (void const* buffer, std::size_t bytes); - void update (int8 const* begin, int8 const* end) + void update (std::int8_t const* begin, std::int8_t const* end) { update (begin, end - begin); } - void update (uint8 const* begin, uint8 const* end) + void update (std::uint8_t const* begin, std::uint8_t const* end) { update (begin, end - begin); } @@ -115,10 +115,10 @@ digest_type const& empty_digest(); void* hash (void const* buffer, std::size_t bytes, void* digest); digest_type& hash ( void const* buffer, std::size_t bytes, digest_type& digest); digest_type hash (void const* buffer, std::size_t bytes); -void* hash (int8 const* begin, int8 const* end, void* digest); -void* hash (uint8 const* begin, uint8 const* end, void* digest); -digest_type hash (int8 const* begin, int8 const* end); -digest_type hash (uint8 const* begin, uint8 const* end); +void* hash (std::int8_t const* begin, std::int8_t const* end, void* digest); +void* hash (std::uint8_t const* begin, std::uint8_t const* end, void* digest); +digest_type hash (std::int8_t const* begin, std::int8_t const* end); +digest_type hash (std::uint8_t const* begin, std::uint8_t const* end); template void* hash (T const& t, void* digest) diff --git a/src/beast/beast/crypto/UnsignedInteger.h b/src/beast/beast/crypto/UnsignedInteger.h index a810b60b3a..4b2069c0ec 100644 --- a/src/beast/beast/crypto/UnsignedInteger.h +++ b/src/beast/beast/crypto/UnsignedInteger.h @@ -23,8 +23,12 @@ #include "UnsignedIntegerCalc.h" #include "MurmurHash.h" -#include "../../modules/beast_core/beast_core.h" // FIX ASAP +#include "../ByteOrder.h" +#include "../utility/hardened_hash.h" +#include "../utility/noexcept.h" +#include +#include #include #include @@ -56,35 +60,20 @@ public: typedef value_type* iterator; typedef value_type const* const_iterator; + void + hash_combine (std::size_t& seed) const noexcept + { + std::size_t result; + Murmur::Hash (get(), size, seed, &result); + seed = result; + } + /** Hardened hash function for use with hash based containers. The seed is used to make the hash unpredictable. This prevents attackers from exploiting crafted inputs to produce degenerate containers. */ - class hasher - { - public: - /** Construct a hash function - If a seed is specified it will be used, else a random seed - will be generated from the system - @param seedToUse An optional seed to use. - */ - explicit hasher (std::size_t seedToUse = Random::getSystemRandom ().nextInt ()) - : m_seed (seedToUse) - { - } - - /** Generates a simple hash from an UnsignedInteger. */ - std::size_t operator() (UnsignedInteger const& key) const - { - std::size_t hash; - Murmur::Hash (key.cbegin (), key.size, m_seed, &hash); - return hash; - } - - private: - std::size_t m_seed; - }; + typedef hardened_hash hasher; /** Determins if two UnsignedInteger objects are equal. */ class equal @@ -126,7 +115,7 @@ public: UnsignedInteger (InputIt first, InputIt last) { m_values [0] = 0; // clear any pad bytes - check_precondition (std::distance (first, last) == size); + assert (std::distance (first, last) == size); std::copy (first, last, begin()); } /** @} */ @@ -150,7 +139,8 @@ public: UnsignedInteger result; value = toNetworkByteOrder (value); result.clear (); - std::memcpy (result.end () - sizeof (value), &value, bmin (Bytes, sizeof (value))); + std::memcpy (result.end () - sizeof (value), &value, + std::min (Bytes, sizeof (value))); return result; } diff --git a/src/beast/beast/crypto/UnsignedIntegerCalc.h b/src/beast/beast/crypto/UnsignedIntegerCalc.h index 2f48049317..05e0ff79d0 100644 --- a/src/beast/beast/crypto/UnsignedIntegerCalc.h +++ b/src/beast/beast/crypto/UnsignedIntegerCalc.h @@ -20,8 +20,11 @@ #ifndef BEAST_CRYPTO_UNSIGNEDINTEGERCALC_H_INCLUDED #define BEAST_CRYPTO_UNSIGNEDINTEGERCALC_H_INCLUDED +#include "../ByteOrder.h" + #include #include +#include namespace beast { @@ -111,7 +114,7 @@ public: if (swizzle) { // Zero fill the possibly uninitialized pad bytes - memset (buffer, 0, + std::memset (buffer, 0, ((sizeof(UInt)-(bytes&(sizeof(UInt)-1)))&(sizeof(UInt)-1))); // Swap and swizzle UInt* lo (values); diff --git a/src/beast/beast/crypto/impl/MurmurHash.cpp b/src/beast/beast/crypto/impl/MurmurHash.cpp index 1674c3b436..4b92e563c2 100644 --- a/src/beast/beast/crypto/impl/MurmurHash.cpp +++ b/src/beast/beast/crypto/impl/MurmurHash.cpp @@ -42,12 +42,12 @@ namespace Murmur { #else -static inline uint32_t rotl32 ( uint32_t x, int8_t r ) +static inline std::uint32_t rotl32 ( std::uint32_t x, int8_t r ) { return (x << r) | (x >> (32 - r)); } -static inline uint64_t rotl64 ( uint64_t x, int8_t r ) +static inline std::uint64_t rotl64 ( std::uint64_t x, int8_t r ) { return (x << r) | (x >> (64 - r)); } @@ -63,12 +63,12 @@ static inline uint64_t rotl64 ( uint64_t x, int8_t r ) // Block read - if your platform needs to do endian-swapping or can only // handle aligned reads, do the conversion here -static forcedinline uint32_t getblock ( const uint32_t* p, int i ) +static inline std::uint32_t getblock ( const std::uint32_t* p, int i ) { return p[i]; } -static forcedinline uint64_t getblock ( const uint64_t* p, int i ) +static inline std::uint64_t getblock ( const std::uint64_t* p, int i ) { return p[i]; } @@ -76,7 +76,7 @@ static forcedinline uint64_t getblock ( const uint64_t* p, int i ) //----------------------------------------------------------------------------- // Finalization mix - force all bits of a hash block to avalanche -static forcedinline uint32_t fmix ( uint32_t h ) +static inline std::uint32_t fmix ( std::uint32_t h ) { h ^= h >> 16; h *= 0x85ebca6b; @@ -89,7 +89,7 @@ static forcedinline uint32_t fmix ( uint32_t h ) //---------- -static forcedinline uint64_t fmix ( uint64_t k ) +static inline std::uint64_t fmix ( std::uint64_t k ) { k ^= k >> 33; k *= BIG_CONSTANT (0xff51afd7ed558ccd); @@ -103,24 +103,24 @@ static forcedinline uint64_t fmix ( uint64_t k ) //----------------------------------------------------------------------------- void MurmurHash3_x86_32 ( const void* key, int len, - uint32_t seed, void* out ) + std::uint32_t seed, void* out ) { const uint8_t* data = (const uint8_t*)key; const int nblocks = len / 4; - uint32_t h1 = seed; + std::uint32_t h1 = seed; - uint32_t c1 = 0xcc9e2d51; - uint32_t c2 = 0x1b873593; + std::uint32_t c1 = 0xcc9e2d51; + std::uint32_t c2 = 0x1b873593; //---------- // body - const uint32_t* blocks = (const uint32_t*) (data + nblocks * 4); + const std::uint32_t* blocks = (const std::uint32_t*) (data + nblocks * 4); for (int i = -nblocks; i; i++) { - uint32_t k1 = getblock (blocks, i); + std::uint32_t k1 = getblock (blocks, i); k1 *= c1; k1 = ROTL32 (k1, 15); @@ -136,7 +136,7 @@ void MurmurHash3_x86_32 ( const void* key, int len, const uint8_t* tail = (const uint8_t*) (data + nblocks * 4); - uint32_t k1 = 0; + std::uint32_t k1 = 0; switch (len & 3) { @@ -161,38 +161,38 @@ void MurmurHash3_x86_32 ( const void* key, int len, h1 = fmix (h1); - * (uint32_t*)out = h1; + * (std::uint32_t*)out = h1; } //----------------------------------------------------------------------------- void MurmurHash3_x86_128 ( const void* key, const int len, - uint32_t seed, void* out ) + std::uint32_t seed, void* out ) { const uint8_t* data = (const uint8_t*)key; const int nblocks = len / 16; - uint32_t h1 = seed; - uint32_t h2 = seed; - uint32_t h3 = seed; - uint32_t h4 = seed; + std::uint32_t h1 = seed; + std::uint32_t h2 = seed; + std::uint32_t h3 = seed; + std::uint32_t h4 = seed; - uint32_t c1 = 0x239b961b; - uint32_t c2 = 0xab0e9789; - uint32_t c3 = 0x38b34ae5; - uint32_t c4 = 0xa1e38b93; + std::uint32_t c1 = 0x239b961b; + std::uint32_t c2 = 0xab0e9789; + std::uint32_t c3 = 0x38b34ae5; + std::uint32_t c4 = 0xa1e38b93; //---------- // body - const uint32_t* blocks = (const uint32_t*) (data + nblocks * 16); + const std::uint32_t* blocks = (const std::uint32_t*) (data + nblocks * 16); for (int i = -nblocks; i; i++) { - uint32_t k1 = getblock (blocks, i * 4 + 0); - uint32_t k2 = getblock (blocks, i * 4 + 1); - uint32_t k3 = getblock (blocks, i * 4 + 2); - uint32_t k4 = getblock (blocks, i * 4 + 3); + std::uint32_t k1 = getblock (blocks, i * 4 + 0); + std::uint32_t k2 = getblock (blocks, i * 4 + 1); + std::uint32_t k3 = getblock (blocks, i * 4 + 2); + std::uint32_t k4 = getblock (blocks, i * 4 + 3); k1 *= c1; k1 = ROTL32 (k1, 15); @@ -236,10 +236,10 @@ void MurmurHash3_x86_128 ( const void* key, const int len, const uint8_t* tail = (const uint8_t*) (data + nblocks * 16); - uint32_t k1 = 0; - uint32_t k2 = 0; - uint32_t k3 = 0; - uint32_t k4 = 0; + std::uint32_t k1 = 0; + std::uint32_t k2 = 0; + std::uint32_t k3 = 0; + std::uint32_t k4 = 0; switch (len & 15) { @@ -348,38 +348,38 @@ void MurmurHash3_x86_128 ( const void* key, const int len, h4 += h1; - ((uint32_t*)out)[0] = h1; + ((std::uint32_t*)out)[0] = h1; - ((uint32_t*)out)[1] = h2; + ((std::uint32_t*)out)[1] = h2; - ((uint32_t*)out)[2] = h3; + ((std::uint32_t*)out)[2] = h3; - ((uint32_t*)out)[3] = h4; + ((std::uint32_t*)out)[3] = h4; } //----------------------------------------------------------------------------- void MurmurHash3_x64_128 ( const void* key, const int len, - const uint32_t seed, void* out ) + const std::uint32_t seed, void* out ) { const uint8_t* data = (const uint8_t*)key; const int nblocks = len / 16; - uint64_t h1 = seed; - uint64_t h2 = seed; + std::uint64_t h1 = seed; + std::uint64_t h2 = seed; - uint64_t c1 = BIG_CONSTANT (0x87c37b91114253d5); - uint64_t c2 = BIG_CONSTANT (0x4cf5ad432745937f); + std::uint64_t c1 = BIG_CONSTANT (0x87c37b91114253d5); + std::uint64_t c2 = BIG_CONSTANT (0x4cf5ad432745937f); //---------- // body - const uint64_t* blocks = (const uint64_t*) (data); + const std::uint64_t* blocks = (const std::uint64_t*) (data); for (int i = 0; i < nblocks; i++) { - uint64_t k1 = getblock (blocks, i * 2 + 0); - uint64_t k2 = getblock (blocks, i * 2 + 1); + std::uint64_t k1 = getblock (blocks, i * 2 + 0); + std::uint64_t k2 = getblock (blocks, i * 2 + 1); k1 *= c1; k1 = ROTL64 (k1, 31); @@ -405,59 +405,59 @@ void MurmurHash3_x64_128 ( const void* key, const int len, const uint8_t* tail = (const uint8_t*) (data + nblocks * 16); - uint64_t k1 = 0; - uint64_t k2 = 0; + std::uint64_t k1 = 0; + std::uint64_t k2 = 0; switch (len & 15) { case 15: - k2 ^= uint64_t (tail[14]) << 48; + k2 ^= std::uint64_t (tail[14]) << 48; case 14: - k2 ^= uint64_t (tail[13]) << 40; + k2 ^= std::uint64_t (tail[13]) << 40; case 13: - k2 ^= uint64_t (tail[12]) << 32; + k2 ^= std::uint64_t (tail[12]) << 32; case 12: - k2 ^= uint64_t (tail[11]) << 24; + k2 ^= std::uint64_t (tail[11]) << 24; case 11: - k2 ^= uint64_t (tail[10]) << 16; + k2 ^= std::uint64_t (tail[10]) << 16; case 10: - k2 ^= uint64_t (tail[ 9]) << 8; + k2 ^= std::uint64_t (tail[ 9]) << 8; case 9: - k2 ^= uint64_t (tail[ 8]) << 0; + k2 ^= std::uint64_t (tail[ 8]) << 0; k2 *= c2; k2 = ROTL64 (k2, 33); k2 *= c1; h2 ^= k2; case 8: - k1 ^= uint64_t (tail[ 7]) << 56; + k1 ^= std::uint64_t (tail[ 7]) << 56; case 7: - k1 ^= uint64_t (tail[ 6]) << 48; + k1 ^= std::uint64_t (tail[ 6]) << 48; case 6: - k1 ^= uint64_t (tail[ 5]) << 40; + k1 ^= std::uint64_t (tail[ 5]) << 40; case 5: - k1 ^= uint64_t (tail[ 4]) << 32; + k1 ^= std::uint64_t (tail[ 4]) << 32; case 4: - k1 ^= uint64_t (tail[ 3]) << 24; + k1 ^= std::uint64_t (tail[ 3]) << 24; case 3: - k1 ^= uint64_t (tail[ 2]) << 16; + k1 ^= std::uint64_t (tail[ 2]) << 16; case 2: - k1 ^= uint64_t (tail[ 1]) << 8; + k1 ^= std::uint64_t (tail[ 1]) << 8; case 1: - k1 ^= uint64_t (tail[ 0]) << 0; + k1 ^= std::uint64_t (tail[ 0]) << 0; k1 *= c1; k1 = ROTL64 (k1, 31); k1 *= c2; @@ -483,9 +483,9 @@ void MurmurHash3_x64_128 ( const void* key, const int len, h2 += h1; - ((uint64_t*)out)[0] = h1; + ((std::uint64_t*)out)[0] = h1; - ((uint64_t*)out)[1] = h2; + ((std::uint64_t*)out)[1] = h2; } } diff --git a/src/beast/beast/crypto/impl/Sha256.cpp b/src/beast/beast/crypto/impl/Sha256.cpp index 3eb1f57743..4fec4b7661 100644 --- a/src/beast/beast/crypto/impl/Sha256.cpp +++ b/src/beast/beast/crypto/impl/Sha256.cpp @@ -49,12 +49,12 @@ Context::Context () void Context::update (void const* buffer, std::size_t bytes) { - detail::SHA256_Update (&m_context, static_cast (buffer), bytes); + detail::SHA256_Update (&m_context, static_cast (buffer), bytes); } void* Context::finish (void* hash) { - detail::SHA256_Final (static_cast (hash), &m_context); + detail::SHA256_Final (static_cast (hash), &m_context); return hash; } @@ -66,7 +66,7 @@ digest_type const& empty_digest() { Holder () { - uint8 zero (0); + std::uint8_t zero (0); hash (zero, digest); } @@ -99,24 +99,24 @@ digest_type hash (void const* buffer, std::size_t bytes) return digest; } -void* hash (int8 const* begin, int8 const* end, void* digest) +void* hash (std::int8_t const* begin, std::int8_t const* end, void* digest) { return hash (begin, end - begin, digest); } -void* hash (uint8 const* begin, uint8 const* end, void* digest) +void* hash (std::uint8_t const* begin, std::uint8_t const* end, void* digest) { return hash (begin, end - begin, digest); } -digest_type hash (int8 const* begin, int8 const* end) +digest_type hash (std::int8_t const* begin, std::int8_t const* end) { digest_type digest; hash (begin, end - begin, digest); return digest; } -digest_type hash (uint8 const* begin, uint8 const* end) +digest_type hash (std::uint8_t const* begin, std::uint8_t const* end) { digest_type digest; hash (begin, end - begin, digest); diff --git a/src/beast/beast/crypto/impl/sha2/sha2.c b/src/beast/beast/crypto/impl/sha2/sha2.c index 125aae2cae..7d4811517d 100644 --- a/src/beast/beast/crypto/impl/sha2/sha2.c +++ b/src/beast/beast/crypto/impl/sha2/sha2.c @@ -103,9 +103,9 @@ * types and pointing out recent ANSI C support for uintXX_t in inttypes.h. */ -typedef uint8 sha2_byte; /* Exactly 1 byte */ -typedef uint32 sha2_word32; /* Exactly 4 bytes */ -typedef uint64 sha2_word64; /* Exactly 8 bytes */ +typedef std::uint8_t sha2_byte; /* Exactly 1 byte */ +typedef std::uint32_t sha2_word32; /* Exactly 4 bytes */ +typedef std::uint64_t sha2_word64; /* Exactly 8 bytes */ /*** SHA-256/384/512 Various Length Definitions ***********************/ /* NOTE: Most of these are in sha2.h */ diff --git a/src/beast/beast/crypto/impl/sha2/sha2.h b/src/beast/beast/crypto/impl/sha2/sha2.h index 1728d86306..f1c4e7e9c5 100644 --- a/src/beast/beast/crypto/impl/sha2/sha2.h +++ b/src/beast/beast/crypto/impl/sha2/sha2.h @@ -58,9 +58,9 @@ /*** SHA-256/384/512 Context Structures *******************************/ typedef struct _SHA512_CTX { - uint64 state[8]; - uint64 bitcount[2]; - uint8 buffer[SHA512_BLOCK_LENGTH]; + std::uint64_t state[8]; + std::uint64_t bitcount[2]; + std::uint8_t buffer[SHA512_BLOCK_LENGTH]; } SHA512_CTX; typedef SHA512_CTX SHA384_CTX; @@ -70,22 +70,22 @@ typedef SHA512_CTX SHA384_CTX; #ifndef NOPROTO void SHA256_Init(Sha256::detail::Context *); -void SHA256_Update(Sha256::detail::Context*, const uint8*, size_t); -void SHA256_Final(uint8[Sha256::digestLength], Sha256::detail::Context*); +void SHA256_Update(Sha256::detail::Context*, const std::uint8_t*, size_t); +void SHA256_Final(std::uint8_t[Sha256::digestLength], Sha256::detail::Context*); char* SHA256_End(Sha256::detail::Context*, char[SHA256_DIGEST_STRING_LENGTH]); -char* SHA256_Data(const uint8*, size_t, char[SHA256_DIGEST_STRING_LENGTH]); +char* SHA256_Data(const std::uint8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH]); void SHA384_Init(SHA384_CTX*); -void SHA384_Update(SHA384_CTX*, const uint8*, size_t); -void SHA384_Final(uint8[SHA384_DIGEST_LENGTH], SHA384_CTX*); +void SHA384_Update(SHA384_CTX*, const std::uint8_t*, size_t); +void SHA384_Final(std::uint8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*); char* SHA384_End(SHA384_CTX*, char[SHA384_DIGEST_STRING_LENGTH]); -char* SHA384_Data(const uint8*, size_t, char[SHA384_DIGEST_STRING_LENGTH]); +char* SHA384_Data(const std::uint8_t*, size_t, char[SHA384_DIGEST_STRING_LENGTH]); void SHA512_Init(SHA512_CTX*); -void SHA512_Update(SHA512_CTX*, const uint8*, size_t); -void SHA512_Final(uint8[SHA512_DIGEST_LENGTH], SHA512_CTX*); +void SHA512_Update(SHA512_CTX*, const std::uint8_t*, size_t); +void SHA512_Final(std::uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*); char* SHA512_End(SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH]); -char* SHA512_Data(const uint8*, size_t, char[SHA512_DIGEST_STRING_LENGTH]); +char* SHA512_Data(const std::uint8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]); #else /* NOPROTO */ diff --git a/src/beast/beast/crypto/tests/BinaryEncoding.test.cpp b/src/beast/beast/crypto/tests/BinaryEncoding.test.cpp index f66185f589..b85a2488f7 100644 --- a/src/beast/beast/crypto/tests/BinaryEncoding.test.cpp +++ b/src/beast/beast/crypto/tests/BinaryEncoding.test.cpp @@ -21,6 +21,7 @@ #include "../UnsignedInteger.h" #include "../../unit_test/suite.h" +#include "../../../modules/beast_core/maths/Random.h" #include #include @@ -134,12 +135,12 @@ public: static std::string encode (UnsignedInteger const& v) { std::string s; - uint8 const* src (v.cbegin()-1); + std::uint8_t const* src (v.cbegin()-1); char const* const tab (alphabet().c_str()); s.reserve (Bytes * 2); for (std::size_t bytes (v.size);bytes--;) { - uint8 const v (*++src); + std::uint8_t const v (*++src); s.push_back (tab [v>>4]); s.push_back (tab [v&0x0f]); } @@ -153,7 +154,7 @@ public: // can't have an odd size if (s.size() & 1) return false; - uint8* dest (rv.begin()-1); + std::uint8_t* dest (rv.begin()-1); int const* const tab (&inverse_alphabet().front()); for (std::string::const_iterator iter (s.begin()); iter != s.end();) { @@ -163,7 +164,7 @@ public: int const n2 (tab [*iter++]); if (n2 == -1) return false; - *++dest = ((uint8)((n1<<4)|n2)); + *++dest = ((std::uint8_t)((n1<<4)|n2)); } return true; } diff --git a/src/beast/beast/http/URL.h b/src/beast/beast/http/URL.h index d2b01f6e55..12e2c31731 100644 --- a/src/beast/beast/http/URL.h +++ b/src/beast/beast/http/URL.h @@ -39,7 +39,7 @@ public: URL ( String schema_, String host_, - uint16 port_, + std::uint16_t port_, String port_string_, String path_, String query_ = "", @@ -68,7 +68,7 @@ public: /** Returns the port number as an integer. If no port was specified, the value will be zero. */ - uint16 port () const; + std::uint16_t port () const; /** Returns the port number as a string. If no port was specified, the string will be empty. @@ -100,7 +100,7 @@ public: private: String m_scheme; String m_host; - uint16 m_port; + std::uint16_t m_port; String m_port_string; String m_path; String m_query; diff --git a/src/beast/beast/http/impl/URL.cpp b/src/beast/beast/http/impl/URL.cpp index 3167684dd0..4aa3810e7d 100644 --- a/src/beast/beast/http/impl/URL.cpp +++ b/src/beast/beast/http/impl/URL.cpp @@ -28,7 +28,7 @@ URL::URL () URL::URL ( String scheme_, String host_, - uint16 port_, + std::uint16_t port_, String port_string_, String path_, String query_, @@ -92,7 +92,7 @@ String URL::port_string () const return m_port_string; } -uint16 URL::port () const +std::uint16_t URL::port () const { return m_port; } diff --git a/src/beast/beast/net/IPAddress.h b/src/beast/beast/net/IPAddress.h index 65e8c32b53..325a10c633 100644 --- a/src/beast/beast/net/IPAddress.h +++ b/src/beast/beast/net/IPAddress.h @@ -20,14 +20,14 @@ #ifndef BEAST_NET_IPADDRESS_H_INCLUDED #define BEAST_NET_IPADDRESS_H_INCLUDED -#include -#include -#include - -#include "../CStdInt.h" #include "IPAddressV4.h" #include "IPAddressV6.h" +#include +#include +#include +#include + //------------------------------------------------------------------------------ namespace beast { diff --git a/src/beast/beast/net/IPAddressV4.h b/src/beast/beast/net/IPAddressV4.h index 529c852a62..cf0c7bd38d 100644 --- a/src/beast/beast/net/IPAddressV4.h +++ b/src/beast/beast/net/IPAddressV4.h @@ -20,12 +20,11 @@ #ifndef BEAST_NET_IPADDRESSV4_H_INCLUDED #define BEAST_NET_IPADDRESSV4_H_INCLUDED -#include +#include #include +#include #include -#include "../CStdInt.h" - namespace beast { namespace IP { @@ -38,12 +37,12 @@ struct AddressV4 /** Construct from a 32-bit unsigned. @note Octets are formed in order from the MSB to the LSB. */ - explicit AddressV4 (uint32 value_); + explicit AddressV4 (std::uint32_t value_); /** Construct from four individual octets.. @note The resulting address is a.b.c.d */ - AddressV4 (uint8 a, uint8 b, uint8 c, uint8 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. @@ -108,7 +107,7 @@ struct AddressV4 { public: typedef typename std::conditional < - IsConst, uint32 const*, uint32*>::type Pointer; + IsConst, std::uint32_t const*, std::uint32_t*>::type Pointer; Proxy (int shift, Pointer value) : m_shift (shift) @@ -116,7 +115,7 @@ struct AddressV4 { } - operator uint8() const + operator std::uint8_t() const { return ((*m_value)>>m_shift) & 0xff; } @@ -141,7 +140,7 @@ struct AddressV4 /** @{ */ /** The value as a 32 bit unsigned. */ - uint32 value; + std::uint32_t value; }; //------------------------------------------------------------------------------ diff --git a/src/beast/beast/net/IPAddressV6.h b/src/beast/beast/net/IPAddressV6.h index f1244e42a8..bc3bb97d50 100644 --- a/src/beast/beast/net/IPAddressV6.h +++ b/src/beast/beast/net/IPAddressV6.h @@ -20,12 +20,12 @@ #ifndef BEAST_NET_IPADDRESSV6_H_INCLUDED #define BEAST_NET_IPADDRESSV6_H_INCLUDED -#include +#include +#include #include +#include #include -#include "../CStdInt.h" - namespace beast { namespace IP { @@ -37,9 +37,9 @@ struct AddressV6 /** Arithmetic comparison. */ /** @{ */ friend bool operator== (AddressV6 const&, AddressV6 const&) - { bassertfalse; return false; } + { assert(false); return false; } friend bool operator< (AddressV6 const&, AddressV6 const&) - { bassertfalse; return false; } + { assert(false); return false; } friend bool operator!= (AddressV6 const& lhs, AddressV6 const& rhs) { return ! (lhs == rhs); } @@ -73,7 +73,7 @@ bool is_public (AddressV6 const& addr); /** boost::hash support. */ inline std::size_t hash_value (AddressV6 const&) - { bassertfalse; return 0; } + { assert(false); return 0; } /** Returns the address represented as a string. */ std::string to_string (AddressV6 const& addr); diff --git a/src/beast/beast/net/IPEndpoint.h b/src/beast/beast/net/IPEndpoint.h index 188b60c184..c9b64ddf4b 100644 --- a/src/beast/beast/net/IPEndpoint.h +++ b/src/beast/beast/net/IPEndpoint.h @@ -20,16 +20,16 @@ #ifndef BEAST_NET_IPENDPOINT_H_INCLUDED #define BEAST_NET_IPENDPOINT_H_INCLUDED -#include -#include - -#include "../CStdInt.h" #include "IPAddress.h" +#include +#include +#include + namespace beast { namespace IP { -typedef uint16 Port; +typedef std::uint16_t Port; /** A version-independent IP address and port combination. */ class Endpoint diff --git a/src/beast/beast/net/detail/Parse.h b/src/beast/beast/net/detail/Parse.h index 415f068cbd..4f4f398b49 100644 --- a/src/beast/beast/net/detail/Parse.h +++ b/src/beast/beast/net/detail/Parse.h @@ -61,16 +61,16 @@ struct integer_holder /** Parse 8-bit unsigned integer. */ template -InputStream& operator>> (InputStream& is, integer_holder const& i) +InputStream& operator>> (InputStream& is, integer_holder const& i) { - uint16 v; + std::uint16_t v; is >> v; if (! (v>=0 && v<=255)) { is.setstate (std::ios_base::failbit); return is; } - i = uint8(v); + i = std::uint8_t(v); return is; } diff --git a/src/beast/beast/net/impl/IPAddressV4.cpp b/src/beast/beast/net/impl/IPAddressV4.cpp index 37af00ef2e..468c770d8c 100644 --- a/src/beast/beast/net/impl/IPAddressV4.cpp +++ b/src/beast/beast/net/impl/IPAddressV4.cpp @@ -34,12 +34,12 @@ AddressV4::AddressV4 () { } -AddressV4::AddressV4 (uint32 value_) +AddressV4::AddressV4 (std::uint32_t value_) : value (value_) { } -AddressV4::AddressV4 (uint8 a, uint8 b, uint8 c, uint8 d) +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) { } @@ -166,7 +166,7 @@ std::string to_string (AddressV4 const& addr) std::istream& operator>> (std::istream& is, AddressV4& addr) { - uint8 octet [4]; + std::uint8_t octet [4]; is >> IP::detail::integer (octet [0]); for (int i = 1; i < 4; ++i) { diff --git a/src/beast/beast/net/tests/IPEndpoint.test.cpp b/src/beast/beast/net/tests/IPEndpoint.test.cpp index ccbee18cce..503aa67ede 100644 --- a/src/beast/beast/net/tests/IPEndpoint.test.cpp +++ b/src/beast/beast/net/tests/IPEndpoint.test.cpp @@ -36,7 +36,7 @@ namespace IP { class IPEndpoint_test : public unit_test::suite { public: - void shouldParseV4 (std::string const& s, uint32 value) + void shouldParseV4 (std::string const& s, std::uint32_t value) { std::pair const result ( AddressV4::from_string (s)); diff --git a/src/beast/beast/smart_ptr/SharedObject.h b/src/beast/beast/smart_ptr/SharedObject.h index 55266c978f..fa0d5ad737 100644 --- a/src/beast/beast/smart_ptr/SharedObject.h +++ b/src/beast/beast/smart_ptr/SharedObject.h @@ -63,7 +63,7 @@ namespace beast { @see SharedPtr, SharedObjectArray, SingleThreadedSharedObject */ -class BEAST_API SharedObject : public Uncopyable +class SharedObject : public Uncopyable { public: //============================================================================== diff --git a/src/beast/beast/strings/CharPointer_ASCII.h b/src/beast/beast/strings/CharPointer_ASCII.h index 4275471140..48e96bb46c 100644 --- a/src/beast/beast/strings/CharPointer_ASCII.h +++ b/src/beast/beast/strings/CharPointer_ASCII.h @@ -87,7 +87,7 @@ public: inline bool isEmpty() const noexcept { return *data == 0; } /** Returns the unicode character that this pointer is pointing to. */ - inline beast_wchar operator*() const noexcept { return (beast_wchar) (uint8) *data; } + inline beast_wchar operator*() const noexcept { return (beast_wchar) (std::uint8_t) *data; } /** Moves this pointer along to the next character in the string. */ inline CharPointer_ASCII operator++() noexcept @@ -105,7 +105,7 @@ public: /** Returns the character that this pointer is currently pointing to, and then advances the pointer to point to the next character. */ - inline beast_wchar getAndAdvance() noexcept { return (beast_wchar) (uint8) *data++; } + inline beast_wchar getAndAdvance() noexcept { return (beast_wchar) (std::uint8_t) *data++; } /** Moves this pointer along to the next character in the string. */ CharPointer_ASCII operator++ (int) noexcept @@ -332,27 +332,27 @@ public: /** Returns true if the first character of this string is a letter or digit. */ bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; } /** Returns true if the first character of this string is upper-case. */ - bool isUpperCase() const { return CharacterFunctions::isUpperCase ((beast_wchar) (uint8) *data) != 0; } + bool isUpperCase() const { return CharacterFunctions::isUpperCase ((beast_wchar) (std::uint8_t) *data) != 0; } /** Returns true if the first character of this string is lower-case. */ - bool isLowerCase() const { return CharacterFunctions::isLowerCase ((beast_wchar) (uint8) *data) != 0; } + bool isLowerCase() const { return CharacterFunctions::isLowerCase ((beast_wchar) (std::uint8_t) *data) != 0; } /** Returns an upper-case version of the first character of this string. */ - beast_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase ((beast_wchar) (uint8) *data); } + beast_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase ((beast_wchar) (std::uint8_t) *data); } /** Returns a lower-case version of the first character of this string. */ - beast_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase ((beast_wchar) (uint8) *data); } + beast_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase ((beast_wchar) (std::uint8_t) *data); } /** Parses this string as a 32-bit integer. */ int getIntValue32() const noexcept { return atoi (data); } /** Parses this string as a 64-bit integer. */ - int64 getIntValue64() const noexcept + std::int64_t getIntValue64() const noexcept { #if BEAST_LINUX || BEAST_ANDROID return atoll (data); #elif BEAST_WINDOWS return _atoi64 (data); #else - return CharacterFunctions::getIntValue (*this); + return CharacterFunctions::getIntValue (*this); #endif } diff --git a/src/beast/beast/strings/CharPointer_UTF16.h b/src/beast/beast/strings/CharPointer_UTF16.h index b34ed4e9e0..987989cbd1 100644 --- a/src/beast/beast/strings/CharPointer_UTF16.h +++ b/src/beast/beast/strings/CharPointer_UTF16.h @@ -26,10 +26,11 @@ #include "../Config.h" #include "../Atomic.h" -#include "../CStdInt.h" #include "CharacterFunctions.h" +#include + namespace beast { //============================================================================== @@ -44,7 +45,7 @@ public: #if BEAST_NATIVE_WCHAR_IS_UTF16 typedef wchar_t CharType; #else - typedef int16 CharType; + typedef std::int16_t CharType; #endif inline explicit CharPointer_UTF16 (const CharType* const rawPointer) noexcept @@ -89,10 +90,10 @@ public: /** Returns the unicode character that this pointer is pointing to. */ beast_wchar operator*() const noexcept { - uint32 n = (uint32) (uint16) *data; + std::uint32_t n = (std::uint32_t) (std::uint16_t) *data; - if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00) - n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00)); + if (n >= 0xd800 && n <= 0xdfff && ((std::uint32_t) (std::uint16_t) data[1]) >= 0xdc00) + n = 0x10000 + (((n - 0xd800) << 10) | (((std::uint32_t) (std::uint16_t) data[1]) - 0xdc00)); return (beast_wchar) n; } @@ -102,7 +103,7 @@ public: { const beast_wchar n = *data++; - if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00) + if (n >= 0xd800 && n <= 0xdfff && ((std::uint32_t) (std::uint16_t) *data) >= 0xdc00) ++data; return *this; @@ -123,10 +124,10 @@ public: advances the pointer to point to the next character. */ beast_wchar getAndAdvance() noexcept { - uint32 n = (uint32) (uint16) *data++; + std::uint32_t n = (std::uint32_t) (std::uint16_t) *data++; - if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00) - n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00))); + if (n >= 0xd800 && n <= 0xdfff && ((std::uint32_t) (std::uint16_t) *data) >= 0xdc00) + n = 0x10000 + ((((n - 0xd800) << 10) | (((std::uint32_t) (std::uint16_t) *data++) - 0xdc00))); return (beast_wchar) n; } @@ -418,12 +419,12 @@ public: } /** Parses this string as a 64-bit integer. */ - int64 getIntValue64() const noexcept + std::int64_t getIntValue64() const noexcept { #if BEAST_WINDOWS return _wtoi64 (data); #else - return CharacterFunctions::getIntValue (*this); + return CharacterFunctions::getIntValue (*this); #endif } @@ -447,7 +448,7 @@ public: while (--maxBytesToRead >= 0 && *dataToTest != 0) { - const uint32 n = (uint32) (uint16) *dataToTest++; + const std::uint32_t n = (std::uint32_t) (std::uint16_t) *dataToTest++; if (n >= 0xd800) { @@ -459,7 +460,7 @@ public: if (n > 0xdc00) return false; - const uint32 nextChar = (uint32) (uint16) *dataToTest++; + const std::uint32_t nextChar = (std::uint32_t) (std::uint16_t) *dataToTest++; if (nextChar < 0xdc00 || nextChar > 0xdfff) return false; @@ -491,10 +492,10 @@ public: static bool isByteOrderMarkBigEndian (const void* possibleByteOrder) noexcept { bassert (possibleByteOrder != nullptr); - const uint8* const c = static_cast (possibleByteOrder); + const std::uint8_t* const c = static_cast (possibleByteOrder); - return c[0] == (uint8) byteOrderMarkBE1 - && c[1] == (uint8) byteOrderMarkBE2; + return c[0] == (std::uint8_t) byteOrderMarkBE1 + && c[1] == (std::uint8_t) byteOrderMarkBE2; } /** Returns true if the first pair of bytes in this pointer are the UTF16 byte-order mark (little endian). @@ -503,10 +504,10 @@ public: static bool isByteOrderMarkLittleEndian (const void* possibleByteOrder) noexcept { bassert (possibleByteOrder != nullptr); - const uint8* const c = static_cast (possibleByteOrder); + const std::uint8_t* const c = static_cast (possibleByteOrder); - return c[0] == (uint8) byteOrderMarkLE1 - && c[1] == (uint8) byteOrderMarkLE2; + return c[0] == (std::uint8_t) byteOrderMarkLE1 + && c[1] == (std::uint8_t) byteOrderMarkLE2; } private: diff --git a/src/beast/beast/strings/CharPointer_UTF32.h b/src/beast/beast/strings/CharPointer_UTF32.h index d5dfa082d0..37ab304ccb 100644 --- a/src/beast/beast/strings/CharPointer_UTF32.h +++ b/src/beast/beast/strings/CharPointer_UTF32.h @@ -341,7 +341,7 @@ public: /** Parses this string as a 32-bit integer. */ int getIntValue32() const noexcept { return CharacterFunctions::getIntValue (*this); } /** Parses this string as a 64-bit integer. */ - int64 getIntValue64() const noexcept { return CharacterFunctions::getIntValue (*this); } + std::int64_t getIntValue64() const noexcept { return CharacterFunctions::getIntValue (*this); } /** Parses this string as a floating point double. */ double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); } diff --git a/src/beast/beast/strings/CharPointer_UTF8.h b/src/beast/beast/strings/CharPointer_UTF8.h index f729c984b1..ac9f709e9f 100644 --- a/src/beast/beast/strings/CharPointer_UTF8.h +++ b/src/beast/beast/strings/CharPointer_UTF8.h @@ -90,11 +90,11 @@ public: const signed char byte = (signed char) *data; if (byte >= 0) - return (beast_wchar) (uint8) byte; + return (beast_wchar) (std::uint8_t) byte; - uint32 n = (uint32) (uint8) byte; - uint32 mask = 0x7f; - uint32 bit = 0x40; + std::uint32_t n = (std::uint32_t) (std::uint8_t) byte; + std::uint32_t mask = 0x7f; + std::uint32_t bit = 0x40; size_t numExtraValues = 0; while ((n & bit) != 0 && bit > 0x10) @@ -108,7 +108,7 @@ public: for (size_t i = 1; i <= numExtraValues; ++i) { - const uint8 nextByte = (uint8) data [i]; + const std::uint8_t nextByte = (std::uint8_t) data [i]; if ((nextByte & 0xc0) != 0x80) break; @@ -157,11 +157,11 @@ public: const signed char byte = (signed char) *data++; if (byte >= 0) - return (beast_wchar) (uint8) byte; + return (beast_wchar) (std::uint8_t) byte; - uint32 n = (uint32) (uint8) byte; - uint32 mask = 0x7f; - uint32 bit = 0x40; + std::uint32_t n = (std::uint32_t) (std::uint8_t) byte; + std::uint32_t mask = 0x7f; + std::uint32_t bit = 0x40; int numExtraValues = 0; while ((n & bit) != 0 && bit > 0x8) @@ -175,7 +175,7 @@ public: while (--numExtraValues >= 0) { - const uint32 nextByte = (uint32) (uint8) *data++; + const std::uint32_t nextByte = (std::uint32_t) (std::uint8_t) *data++; if ((nextByte & 0xc0) != 0x80) break; @@ -248,11 +248,11 @@ public: for (;;) { - const uint32 n = (uint32) (uint8) *d++; + const std::uint32_t n = (std::uint32_t) (std::uint8_t) *d++; if ((n & 0x80) != 0) { - uint32 bit = 0x40; + std::uint32_t bit = 0x40; while ((n & bit) != 0) { @@ -299,7 +299,7 @@ public: static size_t getBytesRequiredFor (const beast_wchar charToWrite) noexcept { size_t num = 1; - const uint32 c = (uint32) charToWrite; + const std::uint32_t c = (std::uint32_t) charToWrite; if (c >= 0x80) { @@ -340,7 +340,7 @@ public: /** Writes a unicode character to this string, and advances this pointer to point to the next position. */ void write (const beast_wchar charToWrite) noexcept { - const uint32 c = (uint32) charToWrite; + const std::uint32_t c = (std::uint32_t) charToWrite; if (c >= 0x80) { @@ -352,7 +352,7 @@ public: ++numExtraBytes; } - *data++ = (CharType) ((uint32) (0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6))); + *data++ = (CharType) ((std::uint32_t) (0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6))); while (--numExtraBytes >= 0) *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6)))); @@ -488,14 +488,14 @@ public: int getIntValue32() const noexcept { return atoi (data); } /** Parses this string as a 64-bit integer. */ - int64 getIntValue64() const noexcept + std::int64_t getIntValue64() const noexcept { #if BEAST_LINUX || BEAST_ANDROID return atoll (data); #elif BEAST_WINDOWS return _atoi64 (data); #else - return CharacterFunctions::getIntValue (*this); + return CharacterFunctions::getIntValue (*this); #endif } @@ -520,7 +520,7 @@ public: if (byte < 0) { - uint8 bit = 0x40; + std::uint8_t bit = 0x40; int numExtraValues = 0; while ((byte & bit) != 0) @@ -569,11 +569,11 @@ public: static bool isByteOrderMark (const void* possibleByteOrder) noexcept { bassert (possibleByteOrder != nullptr); - const uint8* const c = static_cast (possibleByteOrder); + const std::uint8_t* const c = static_cast (possibleByteOrder); - return c[0] == (uint8) byteOrderMark1 - && c[1] == (uint8) byteOrderMark2 - && c[2] == (uint8) byteOrderMark3; + return c[0] == (std::uint8_t) byteOrderMark1 + && c[1] == (std::uint8_t) byteOrderMark2 + && c[2] == (std::uint8_t) byteOrderMark3; } private: diff --git a/src/beast/beast/strings/CharacterFunctions.h b/src/beast/beast/strings/CharacterFunctions.h index f369544129..d05bcdd6db 100644 --- a/src/beast/beast/strings/CharacterFunctions.h +++ b/src/beast/beast/strings/CharacterFunctions.h @@ -27,9 +27,10 @@ #include #include "../Config.h" -#include "../CStdInt.h" #include "../Memory.h" +#include + namespace beast { //============================================================================== @@ -50,7 +51,7 @@ namespace beast { /** A platform-independent 32-bit unicode character type. */ typedef wchar_t beast_wchar; #else - typedef uint32 beast_wchar; + typedef std::uint32_t beast_wchar; #endif #ifndef DOXYGEN @@ -78,7 +79,7 @@ namespace beast { @see String, CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32 */ -class BEAST_API CharacterFunctions +class CharacterFunctions { public: //============================================================================== diff --git a/src/beast/beast/strings/NewLine.h b/src/beast/beast/strings/NewLine.h index 23dfb0c058..1566402d0a 100644 --- a/src/beast/beast/strings/NewLine.h +++ b/src/beast/beast/strings/NewLine.h @@ -41,7 +41,7 @@ namespace beast { The exact character sequence that will be used for the new-line can be set and retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString(). */ -class BEAST_API NewLine +class NewLine { public: /** Returns the default new-line sequence that the library uses. @@ -72,7 +72,7 @@ extern NewLine newLine; myString << "Hello World" << newLine << newLine; @endcode */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, const NewLine&); +String& operator<< (String& string1, const NewLine&); } diff --git a/src/beast/beast/strings/String.h b/src/beast/beast/strings/String.h index 198408ac55..db7a0df480 100644 --- a/src/beast/beast/strings/String.h +++ b/src/beast/beast/strings/String.h @@ -25,7 +25,6 @@ #define BEAST_STRINGS_STRING_H_INCLUDED #include "../Config.h" -#include "../CStdInt.h" #include "../Memory.h" #include "CharacterFunctions.h" @@ -44,6 +43,7 @@ #include "StringFromNumber.h" #include "String.h" +#include #include namespace beast { @@ -66,7 +66,7 @@ namespace beast { @see StringArray, StringPairArray */ -class BEAST_API String +class String { public: //============================================================================== @@ -193,7 +193,7 @@ public: int hashCode() const noexcept; /** Generates a probably-unique 64-bit hashcode from this string. */ - int64 hashCode64() const noexcept; + std::int64_t hashCode64() const noexcept; /** Returns a hash value suitable for use with std::hash. */ std::size_t hash() const noexcept; @@ -920,15 +920,13 @@ public: */ explicit String (unsigned short decimalInteger); - /** Creates a string containing this signed 64-bit integer as a decimal number. - @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString - */ - explicit String (int64 largeIntegerValue); + explicit String (long largeIntegerValue); - /** Creates a string containing this unsigned 64-bit integer as a decimal number. - @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString - */ - explicit String (uint64 largeIntegerValue); + explicit String (unsigned long largeIntegerValue); + + explicit String (long long largeIntegerValue); + + explicit String (unsigned long long largeIntegerValue); /** Creates a string representing this floating-point number. @param floatValue the value to convert to a string @@ -971,7 +969,7 @@ public: @returns the value of the string as a 64 bit signed base-10 integer. */ - int64 getLargeIntValue() const noexcept; + std::int64_t getLargeIntValue() const noexcept; /** Parses a decimal number from the end of the string. @@ -1018,13 +1016,13 @@ public: @returns a 64-bit number which is the value of the string in hex. */ - int64 getHexValue64() const noexcept; + std::int64_t getHexValue64() const noexcept; /** Creates a string representing this 32-bit value in hexadecimal. */ static String toHexString (int number); /** Creates a string representing this 64-bit value in hexadecimal. */ - static String toHexString (int64 number); + static String toHexString (std::int64_t number); /** Creates a string representing this 16-bit value in hexadecimal. */ static String toHexString (short number); @@ -1273,103 +1271,103 @@ inline String String::fromNumber (double number, int numberOfDecimalPla //------------------------------------------------------------------------------ /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (const char* string1, const String& string2); +String operator+ (const char* string1, const String& string2); /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (const wchar_t* string1, const String& string2); +String operator+ (const wchar_t* string1, const String& string2); /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (char string1, const String& string2); +String operator+ (char string1, const String& string2); /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (wchar_t string1, const String& string2); +String operator+ (wchar_t string1, const String& string2); #if ! BEAST_NATIVE_WCHAR_IS_UTF32 /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (beast_wchar string1, const String& string2); +String operator+ (beast_wchar string1, const String& string2); #endif /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (String string1, const String& string2); +String operator+ (String string1, const String& string2); /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (String string1, const char* string2); +String operator+ (String string1, const char* string2); /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (String string1, const wchar_t* string2); +String operator+ (String string1, const wchar_t* string2); /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (String string1, char characterToAppend); +String operator+ (String string1, char characterToAppend); /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (String string1, wchar_t characterToAppend); +String operator+ (String string1, wchar_t characterToAppend); #if ! BEAST_NATIVE_WCHAR_IS_UTF32 /** Concatenates two strings. */ -BEAST_API String BEAST_CALLTYPE operator+ (String string1, beast_wchar characterToAppend); +String operator+ (String string1, beast_wchar characterToAppend); #endif //============================================================================== /** Appends a character at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, char characterToAppend); +String& operator<< (String& string1, char characterToAppend); /** Appends a character at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, wchar_t characterToAppend); +String& operator<< (String& string1, wchar_t characterToAppend); #if ! BEAST_NATIVE_WCHAR_IS_UTF32 /** Appends a character at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, beast_wchar characterToAppend); +String& operator<< (String& string1, beast_wchar characterToAppend); #endif /** Appends a string to the end of the first one. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, const char* string2); +String& operator<< (String& string1, const char* string2); /** Appends a string to the end of the first one. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, const wchar_t* string2); +String& operator<< (String& string1, const wchar_t* string2); /** Appends a string to the end of the first one. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, const String& string2); +String& operator<< (String& string1, const String& string2); /** Appends a decimal number at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, short number); +String& operator<< (String& string1, short number); /** Appends a decimal number at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, int number); +String& operator<< (String& string1, int number); /** Appends a decimal number at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, long number); +String& operator<< (String& string1, long number); /** Appends a decimal number at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, int64 number); +String& operator<< (String& string1, std::int64_t number); /** Appends a decimal number at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, float number); +String& operator<< (String& string1, float number); /** Appends a decimal number at the end of a string. */ -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, double number); +String& operator<< (String& string1, double number); //============================================================================== /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator== (const String& string1, const String& string2) noexcept; +bool operator== (const String& string1, const String& string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator== (const String& string1, const char* string2) noexcept; +bool operator== (const String& string1, const char* string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator== (const String& string1, const wchar_t* string2) noexcept; +bool operator== (const String& string1, const wchar_t* string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator== (const String& string1, const CharPointer_UTF8 string2) noexcept; +bool operator== (const String& string1, const CharPointer_UTF8 string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator== (const String& string1, const CharPointer_UTF16 string2) noexcept; +bool operator== (const String& string1, const CharPointer_UTF16 string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator== (const String& string1, const CharPointer_UTF32 string2) noexcept; +bool operator== (const String& string1, const CharPointer_UTF32 string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator!= (const String& string1, const String& string2) noexcept; +bool operator!= (const String& string1, const String& string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator!= (const String& string1, const char* string2) noexcept; +bool operator!= (const String& string1, const char* string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator!= (const String& string1, const wchar_t* string2) noexcept; +bool operator!= (const String& string1, const wchar_t* string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8 string2) noexcept; +bool operator!= (const String& string1, const CharPointer_UTF8 string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16 string2) noexcept; +bool operator!= (const String& string1, const CharPointer_UTF16 string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32 string2) noexcept; +bool operator!= (const String& string1, const CharPointer_UTF32 string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator> (const String& string1, const String& string2) noexcept; +bool operator> (const String& string1, const String& string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator< (const String& string1, const String& string2) noexcept; +bool operator< (const String& string1, const String& string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator>= (const String& string1, const String& string2) noexcept; +bool operator>= (const String& string1, const String& string2) noexcept; /** Case-sensitive comparison of two strings. */ -BEAST_API bool BEAST_CALLTYPE operator<= (const String& string1, const String& string2) noexcept; +bool operator<= (const String& string1, const String& string2) noexcept; //============================================================================== /** This operator allows you to write a beast String directly to std output streams. This is handy for writing strings to std::cout, std::cerr, etc. */ template -std::basic_ostream & BEAST_CALLTYPE operator<< (std::basic_ostream & stream, const String& stringToWrite) +std::basic_ostream & operator<< (std::basic_ostream & stream, const String& stringToWrite) { return stream << stringToWrite.toRawUTF8(); } @@ -1378,7 +1376,7 @@ std::basic_ostream & BEAST_CALLTYPE operator<< (std::basic_ostream This is handy for writing strings to std::wcout, std::wcerr, etc. */ template -std::basic_ostream & BEAST_CALLTYPE operator<< (std::basic_ostream & stream, const String& stringToWrite) +std::basic_ostream & operator<< (std::basic_ostream & stream, const String& stringToWrite) { return stream << stringToWrite.toWideCharPointer(); } diff --git a/src/beast/beast/strings/StringFromNumber.h b/src/beast/beast/strings/StringFromNumber.h index b50a989e2b..21d8438b09 100644 --- a/src/beast/beast/strings/StringFromNumber.h +++ b/src/beast/beast/strings/StringFromNumber.h @@ -75,13 +75,13 @@ public: if (std::numeric_limits ::is_signed) { if (n >= 0) - return printDigits (t, static_cast (n)); + return printDigits (t, static_cast (n)); // NB: this needs to be careful not to call - // -std::numeric_limits::min(), + // -std::numeric_limits::min(), // which has undefined behaviour // - t = printDigits (t, static_cast (-(n + 1)) + 1); + t = printDigits (t, static_cast (-(n + 1)) + 1); *--t = '-'; return t; } @@ -123,7 +123,7 @@ public: { char* const end = buffer + numChars; char* t = end; - int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5); + std::int64_t v = (std::int64_t) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5); *--t = (char) 0; while (numDecPlaces >= 0 || v > 0) diff --git a/src/beast/beast/strings/impl/String.cpp b/src/beast/beast/strings/impl/String.cpp index 8a52c1ecca..a9e19a44a8 100644 --- a/src/beast/beast/strings/impl/String.cpp +++ b/src/beast/beast/strings/impl/String.cpp @@ -381,8 +381,10 @@ String::String (const int number) : text (NumberToStringConverters::c String::String (const unsigned int number) : text (NumberToStringConverters::createFromInteger (number)) {} String::String (const short number) : text (NumberToStringConverters::createFromInteger ((int) number)) {} String::String (const unsigned short number) : text (NumberToStringConverters::createFromInteger ((unsigned int) number)) {} -String::String (const int64 number) : text (NumberToStringConverters::createFromInteger (number)) {} -String::String (const uint64 number) : text (NumberToStringConverters::createFromInteger (number)) {} +String::String (const long number) : text (NumberToStringConverters::createFromInteger (number)) {} +String::String (const unsigned long number) : text (NumberToStringConverters::createFromInteger (number)) {} +String::String (const long long number) : text (NumberToStringConverters::createFromInteger (number)) {} +String::String (const unsigned long long number) : text (NumberToStringConverters::createFromInteger (number)) {} String::String (const float number) : text (NumberToStringConverters::createFromDouble ((double) number, 0)) {} String::String (const double number) : text (NumberToStringConverters::createFromDouble (number, 0)) {} @@ -434,9 +436,9 @@ int String::hashCode() const noexcept return detail::HashGenerator ::calculate (text); } -int64 String::hashCode64() const noexcept +std::int64_t String::hashCode64() const noexcept { - return detail::HashGenerator ::calculate (text); + return detail::HashGenerator ::calculate (text); } std::size_t String::hash() const noexcept @@ -445,22 +447,22 @@ std::size_t String::hash() const noexcept } //============================================================================== -BEAST_API bool BEAST_CALLTYPE operator== (const String& s1, const String& s2) noexcept { return s1.compare (s2) == 0; } -BEAST_API bool BEAST_CALLTYPE operator== (const String& s1, const char* const s2) noexcept { return s1.compare (s2) == 0; } -BEAST_API bool BEAST_CALLTYPE operator== (const String& s1, const wchar_t* const s2) noexcept { return s1.compare (s2) == 0; } -BEAST_API bool BEAST_CALLTYPE operator== (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } -BEAST_API bool BEAST_CALLTYPE operator== (const String& s1, const CharPointer_UTF16 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } -BEAST_API bool BEAST_CALLTYPE operator== (const String& s1, const CharPointer_UTF32 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } -BEAST_API bool BEAST_CALLTYPE operator!= (const String& s1, const String& s2) noexcept { return s1.compare (s2) != 0; } -BEAST_API bool BEAST_CALLTYPE operator!= (const String& s1, const char* const s2) noexcept { return s1.compare (s2) != 0; } -BEAST_API bool BEAST_CALLTYPE operator!= (const String& s1, const wchar_t* const s2) noexcept { return s1.compare (s2) != 0; } -BEAST_API bool BEAST_CALLTYPE operator!= (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } -BEAST_API bool BEAST_CALLTYPE operator!= (const String& s1, const CharPointer_UTF16 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } -BEAST_API bool BEAST_CALLTYPE operator!= (const String& s1, const CharPointer_UTF32 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } -BEAST_API bool BEAST_CALLTYPE operator> (const String& s1, const String& s2) noexcept { return s1.compare (s2) > 0; } -BEAST_API bool BEAST_CALLTYPE operator< (const String& s1, const String& s2) noexcept { return s1.compare (s2) < 0; } -BEAST_API bool BEAST_CALLTYPE operator>= (const String& s1, const String& s2) noexcept { return s1.compare (s2) >= 0; } -BEAST_API bool BEAST_CALLTYPE operator<= (const String& s1, const String& s2) noexcept { return s1.compare (s2) <= 0; } +bool operator== (const String& s1, const String& s2) noexcept { return s1.compare (s2) == 0; } +bool operator== (const String& s1, const char* const s2) noexcept { return s1.compare (s2) == 0; } +bool operator== (const String& s1, const wchar_t* const s2) noexcept { return s1.compare (s2) == 0; } +bool operator== (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } +bool operator== (const String& s1, const CharPointer_UTF16 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } +bool operator== (const String& s1, const CharPointer_UTF32 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; } +bool operator!= (const String& s1, const String& s2) noexcept { return s1.compare (s2) != 0; } +bool operator!= (const String& s1, const char* const s2) noexcept { return s1.compare (s2) != 0; } +bool operator!= (const String& s1, const wchar_t* const s2) noexcept { return s1.compare (s2) != 0; } +bool operator!= (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } +bool operator!= (const String& s1, const CharPointer_UTF16 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } +bool operator!= (const String& s1, const CharPointer_UTF32 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; } +bool operator> (const String& s1, const String& s2) noexcept { return s1.compare (s2) > 0; } +bool operator< (const String& s1, const String& s2) noexcept { return s1.compare (s2) < 0; } +bool operator>= (const String& s1, const String& s2) noexcept { return s1.compare (s2) >= 0; } +bool operator<= (const String& s1, const String& s2) noexcept { return s1.compare (s2) <= 0; } bool String::equalsIgnoreCase (const wchar_t* const t) const noexcept { @@ -612,52 +614,52 @@ String& String::operator+= (const int number) } //============================================================================== -BEAST_API String BEAST_CALLTYPE operator+ (const char* const string1, const String& string2) +String operator+ (const char* const string1, const String& string2) { String s (string1); return s += string2; } -BEAST_API String BEAST_CALLTYPE operator+ (const wchar_t* const string1, const String& string2) +String operator+ (const wchar_t* const string1, const String& string2) { String s (string1); return s += string2; } -BEAST_API String BEAST_CALLTYPE operator+ (const char s1, const String& s2) { return String::charToString ((beast_wchar) (uint8) s1) + s2; } -BEAST_API String BEAST_CALLTYPE operator+ (const wchar_t s1, const String& s2) { return String::charToString (s1) + s2; } +String operator+ (const char s1, const String& s2) { return String::charToString ((beast_wchar) (std::uint8_t) s1) + s2; } +String operator+ (const wchar_t s1, const String& s2) { return String::charToString (s1) + s2; } #if ! BEAST_NATIVE_WCHAR_IS_UTF32 -BEAST_API String BEAST_CALLTYPE operator+ (const beast_wchar s1, const String& s2) { return String::charToString (s1) + s2; } +String operator+ (const beast_wchar s1, const String& s2) { return String::charToString (s1) + s2; } #endif -BEAST_API String BEAST_CALLTYPE operator+ (String s1, const String& s2) { return s1 += s2; } -BEAST_API String BEAST_CALLTYPE operator+ (String s1, const char* const s2) { return s1 += s2; } -BEAST_API String BEAST_CALLTYPE operator+ (String s1, const wchar_t* s2) { return s1 += s2; } +String operator+ (String s1, const String& s2) { return s1 += s2; } +String operator+ (String s1, const char* const s2) { return s1 += s2; } +String operator+ (String s1, const wchar_t* s2) { return s1 += s2; } -BEAST_API String BEAST_CALLTYPE operator+ (String s1, const char s2) { return s1 += s2; } -BEAST_API String BEAST_CALLTYPE operator+ (String s1, const wchar_t s2) { return s1 += s2; } +String operator+ (String s1, const char s2) { return s1 += s2; } +String operator+ (String s1, const wchar_t s2) { return s1 += s2; } #if ! BEAST_NATIVE_WCHAR_IS_UTF32 -BEAST_API String BEAST_CALLTYPE operator+ (String s1, const beast_wchar s2) { return s1 += s2; } +String operator+ (String s1, const beast_wchar s2) { return s1 += s2; } #endif -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const char s2) { return s1 += s2; } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const wchar_t s2) { return s1 += s2; } +String& operator<< (String& s1, const char s2) { return s1 += s2; } +String& operator<< (String& s1, const wchar_t s2) { return s1 += s2; } #if ! BEAST_NATIVE_WCHAR_IS_UTF32 -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const beast_wchar s2) { return s1 += s2; } +String& operator<< (String& s1, const beast_wchar s2) { return s1 += s2; } #endif -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const char* const s2) { return s1 += s2; } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const wchar_t* const s2) { return s1 += s2; } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const String& s2) { return s1 += s2; } +String& operator<< (String& s1, const char* const s2) { return s1 += s2; } +String& operator<< (String& s1, const wchar_t* const s2) { return s1 += s2; } +String& operator<< (String& s1, const String& s2) { return s1 += s2; } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const short number) { return s1 += (int) number; } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const int number) { return s1 += number; } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const long number) { return s1 += (int) number; } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const int64 number) { return s1 << String (number); } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const float number) { return s1 += String (number); } -BEAST_API String& BEAST_CALLTYPE operator<< (String& s1, const double number) { return s1 += String (number); } +String& operator<< (String& s1, const short number) { return s1 += (int) number; } +String& operator<< (String& s1, const int number) { return s1 += number; } +String& operator<< (String& s1, const long number) { return s1 += (int) number; } +String& operator<< (String& s1, const long long number) { return s1 << String (number); } +String& operator<< (String& s1, const float number) { return s1 += String (number); } +String& operator<< (String& s1, const double number) { return s1 += String (number); } -BEAST_API String& BEAST_CALLTYPE operator<< (String& string1, const NewLine&) +String& operator<< (String& string1, const NewLine&) { return string1 += NewLine::getDefault(); } @@ -1711,7 +1713,7 @@ int String::getTrailingIntValue() const noexcept return n; } -int64 String::getLargeIntValue() const noexcept +std::int64_t String::getLargeIntValue() const noexcept { return text.getIntValue64(); } @@ -1769,9 +1771,9 @@ String String::toHexString (const int number) return HexConverter ::hexToString ((unsigned int) number); } -String String::toHexString (const int64 number) +String String::toHexString (const std::int64_t number) { - return HexConverter ::hexToString ((uint64) number); + return HexConverter ::hexToString ((std::uint64_t) number); } String String::toHexString (const short number) @@ -1808,12 +1810,12 @@ String String::toHexString (const void* const d, const int size, const int group } int String::getHexValue32() const noexcept { return HexConverter ::stringToHex (text); } -int64 String::getHexValue64() const noexcept { return HexConverter::stringToHex (text); } +std::int64_t String::getHexValue64() const noexcept { return HexConverter::stringToHex (text); } //============================================================================== String String::createStringFromData (const void* const unknownData, const int size) { - const uint8* const data = static_cast (unknownData); + const std::uint8_t* const data = static_cast (unknownData); if (size <= 0 || data == nullptr) return empty; @@ -1828,7 +1830,7 @@ String String::createStringFromData (const void* const unknownData, const int si StringCreationHelper builder ((size_t) numChars); - const uint16* const src = (const uint16*) (data + 2); + const std::uint16_t* const src = (const std::uint16_t*) (data + 2); if (CharPointer_UTF16::isByteOrderMarkBigEndian (data)) { @@ -1845,7 +1847,7 @@ String String::createStringFromData (const void* const unknownData, const int si return builder.result; } - const uint8* start = data; + const std::uint8_t* start = data; if (size >= 3 && CharPointer_UTF8::isByteOrderMark (data)) start += 3; @@ -1932,7 +1934,7 @@ struct StringCopier { static size_t copyToBuffer (const CharPointerType_Src source, typename CharPointerType_Dest::CharType* const buffer, const size_t maxBufferSizeBytes) { - bassert (((ssize_t) maxBufferSizeBytes) >= 0); // keep this value positive! + bassert (((std::ptrdiff_t) maxBufferSizeBytes) >= 0); // keep this value positive! if (buffer == nullptr) return CharPointerType_Dest::getBytesRequiredFor (source) + sizeof (typename CharPointerType_Dest::CharType); diff --git a/src/beast/beast/threads/ServiceQueue.h b/src/beast/beast/threads/ServiceQueue.h index 8f2134e79b..c001865c68 100644 --- a/src/beast/beast/threads/ServiceQueue.h +++ b/src/beast/beast/threads/ServiceQueue.h @@ -74,13 +74,13 @@ public: static Page* create (size_type pageBytes) { - return new (new uint8[pageBytes + overhead()]) Page (pageBytes); + return new (new std::uint8_t[pageBytes + overhead()]) Page (pageBytes); } static void destroy (Page* page) { page->~Page(); - delete[] ((uint8*)page); + delete[] ((std::uint8_t*)page); } void reset () @@ -599,10 +599,10 @@ private: (*item)(); - typename Allocator::template rebind ::other a (m_alloc); + typename Allocator::template rebind ::other a (m_alloc); std::size_t const size (item->size()); item->~Item(); - a.deallocate (reinterpret_cast(item), size); + a.deallocate (reinterpret_cast(item), size); return 1; } diff --git a/src/beast/beast/threads/SpinLock.h b/src/beast/beast/threads/SpinLock.h index 88e21fcdbd..4750911eb5 100644 --- a/src/beast/beast/threads/SpinLock.h +++ b/src/beast/beast/threads/SpinLock.h @@ -44,7 +44,7 @@ namespace beast { @see CriticalSection */ -class BEAST_API SpinLock : public Uncopyable +class SpinLock : public Uncopyable { public: /** Provides the type of scoped lock to use for locking a SpinLock. */ diff --git a/src/beast/beast/threads/Thread.h b/src/beast/beast/threads/Thread.h index 4a89fe4657..aee57d5f0d 100644 --- a/src/beast/beast/threads/Thread.h +++ b/src/beast/beast/threads/Thread.h @@ -45,7 +45,7 @@ namespace beast { @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow, MessageManagerLock */ -class BEAST_API Thread : LeakChecked , public Uncopyable +class Thread : LeakChecked , public Uncopyable { public: //============================================================================== @@ -185,7 +185,7 @@ public: @see setCurrentThreadAffinityMask */ - void setAffinityMask (uint32 affinityMask); + void setAffinityMask (std::uint32_t affinityMask); /** Changes the affinity mask for the caller thread. @@ -193,14 +193,14 @@ public: @see setAffinityMask */ - static void setCurrentThreadAffinityMask (uint32 affinityMask); + static void setCurrentThreadAffinityMask (std::uint32_t affinityMask); //============================================================================== // this can be called from any thread that needs to pause.. - static void BEAST_CALLTYPE sleep (int milliseconds); + static void sleep (int milliseconds); /** Yields the calling thread's current time-slot. */ - static void BEAST_CALLTYPE yield(); + static void yield(); //============================================================================== /** Makes the thread wait for a notification. @@ -275,11 +275,11 @@ private: RecursiveMutex startStopLock; WaitableEvent startSuspensionEvent, defaultEvent; int threadPriority; - uint32 affinityMask; + std::uint32_t affinityMask; bool volatile shouldExit; #ifndef DOXYGEN - friend void BEAST_API beast_threadEntryPoint (void*); + friend void beast_threadEntryPoint (void*); #endif void launchThread(); diff --git a/src/beast/beast/threads/impl/Thread.cpp b/src/beast/beast/threads/impl/Thread.cpp index 34c2b71fca..2aa08401bc 100644 --- a/src/beast/beast/threads/impl/Thread.cpp +++ b/src/beast/beast/threads/impl/Thread.cpp @@ -106,7 +106,7 @@ void Thread::threadEntryPoint() } // used to wrap the incoming call from the platform-specific code -void BEAST_API beast_threadEntryPoint (void* userData) +void beast_threadEntryPoint (void* userData) { static_cast (userData)->threadEntryPoint(); } @@ -162,7 +162,7 @@ bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const // Doh! So how exactly do you expect this thread to wait for itself to stop?? bassert (getThreadId() != getCurrentThreadId() || getCurrentThreadId() == 0); - const uint32 timeoutEnd = Time::getMillisecondCounter() + (uint32) timeOutMilliseconds; + const std::uint32_t timeoutEnd = Time::getMillisecondCounter() + (std::uint32_t) timeOutMilliseconds; while (isThreadRunning()) { @@ -252,7 +252,7 @@ bool Thread::setCurrentThreadPriority (const int newPriority) return setThreadPriority (0, newPriority); } -void Thread::setAffinityMask (const uint32 newAffinityMask) +void Thread::setAffinityMask (const std::uint32_t newAffinityMask) { affinityMask = newAffinityMask; } @@ -299,7 +299,7 @@ namespace beast { HWND beast_messageWindowHandle = 0; // (this is used by other parts of the codebase) -void BEAST_API beast_threadEntryPoint (void*); +void beast_threadEntryPoint (void*); static unsigned int __stdcall threadEntryProc (void* userData) { @@ -367,7 +367,7 @@ void Thread::setCurrentThreadName (const String& name) Thread::ThreadID Thread::getCurrentThreadId() { - return (ThreadID) (pointer_sized_int) GetCurrentThreadId(); + return (ThreadID) (std::intptr_t) GetCurrentThreadId(); } bool Thread::setThreadPriority (void* handle, int priority) @@ -387,7 +387,7 @@ bool Thread::setThreadPriority (void* handle, int priority) return SetThreadPriority (handle, pri) != FALSE; } -void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) +void Thread::setCurrentThreadAffinityMask (const std::uint32_t affinityMask) { SetThreadAffinityMask (GetCurrentThread(), affinityMask); } @@ -414,7 +414,7 @@ struct SleepEvent static SleepEvent sleepEvent; -void BEAST_CALLTYPE Thread::sleep (const int millisecs) +void Thread::sleep (const int millisecs) { if (millisecs >= 10 || sleepEvent.handle == 0) { @@ -458,7 +458,7 @@ namespace beast{ namespace beast { -void BEAST_CALLTYPE Thread::sleep (int millisecs) +void Thread::sleep (int millisecs) { struct timespec time; time.tv_sec = millisecs / 1000; @@ -466,7 +466,7 @@ void BEAST_CALLTYPE Thread::sleep (int millisecs) nanosleep (&time, nullptr); } -void BEAST_API beast_threadEntryPoint (void*); +void beast_threadEntryPoint (void*); extern "C" void* threadEntryProcBeast (void*); extern "C" void* threadEntryProcBeast (void* userData) @@ -576,7 +576,7 @@ void Thread::yield() #define SUPPORT_AFFINITIES 1 #endif -void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) +void Thread::setCurrentThreadAffinityMask (const std::uint32_t affinityMask) { #if SUPPORT_AFFINITIES cpu_set_t affinity; diff --git a/src/beast/beast/threads/tests/Atomic.test.cpp b/src/beast/beast/threads/tests/Atomic.test.cpp index a348c435c6..f6e7640671 100644 --- a/src/beast/beast/threads/tests/Atomic.test.cpp +++ b/src/beast/beast/threads/tests/Atomic.test.cpp @@ -93,9 +93,9 @@ public: int a2[3]; expect (numElementsInArray(a2) == 3); - expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211); - expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211); - expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211)); + expect (ByteOrder::swap ((std::uint16_t) 0x1122) == 0x2211); + expect (ByteOrder::swap ((std::uint32_t) 0x11223344) == 0x44332211); + expect (ByteOrder::swap ((std::uint64_t) 0x1122334455667788LL) == 0x8877665544332211LL); testcase ("int"); testInteger (); @@ -103,11 +103,11 @@ public: testcase ("unsigned int"); testInteger (); - testcase ("int32"); - testInteger (); + testcase ("std::int32_t"); + testInteger (); - testcase ("uint32"); - testInteger (); + testcase ("std::uint32_t"); + testInteger (); testcase ("long"); testInteger (); @@ -122,11 +122,11 @@ public: testFloat (); #if ! BEAST_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms - testcase ("int64"); - testInteger (); + testcase ("std::int64_t"); + testInteger (); - testcase ("uint64"); - testInteger (); + testcase ("std::uint64_t"); + testInteger (); testcase ("double"); testFloat (); diff --git a/src/beast/beast/threads/tests/ServiceQueue.test.cpp b/src/beast/beast/threads/tests/ServiceQueue.test.cpp index f079d57421..f90aa649f0 100644 --- a/src/beast/beast/threads/tests/ServiceQueue.test.cpp +++ b/src/beast/beast/threads/tests/ServiceQueue.test.cpp @@ -39,11 +39,11 @@ public: void start () { m_startTime = Time::getHighResolutionTicks (); } double getElapsed () { - int64 const now = Time::getHighResolutionTicks(); + std::int64_t const now = Time::getHighResolutionTicks(); return Time::highResolutionTicksToSeconds (now - m_startTime); } private: - int64 m_startTime; + std::int64_t m_startTime; }; static int const callsPerThread = 50000; @@ -57,7 +57,7 @@ public: Random m_random; String m_string; - Consumer (int id, int64 seedValue, ServiceType& service) + Consumer (int id, std::int64_t seedValue, ServiceType& service) : Thread ("C#" + String::fromNumber (id)) , m_service (service) , m_random (seedValue) @@ -103,7 +103,7 @@ public: Random m_random; String m_string; - Producer (int id, int64 seedValue, ServiceType& service) + Producer (int id, std::int64_t seedValue, ServiceType& service) : Thread ("P#" + String::fromNumber (id)) , m_service (service) , m_random (seedValue) @@ -208,7 +208,7 @@ public: ServiceQueue& m_service; String m_string; - ServiceThread (int id, int64 seedValue, + ServiceThread (int id, std::int64_t seedValue, ServiceQueue& service) : Thread ("#" + String::fromNumber (id)) , m_random (seedValue) diff --git a/src/beast/beast/utility/PropertyStream.h b/src/beast/beast/utility/PropertyStream.h index 3d0a5bc1ad..480b8db4d8 100644 --- a/src/beast/beast/utility/PropertyStream.h +++ b/src/beast/beast/utility/PropertyStream.h @@ -20,7 +20,6 @@ #ifndef BEAST_UTILITY_PROPERTYSTREAM_H_INCLUDED #define BEAST_UTILITY_PROPERTYSTREAM_H_INCLUDED -#include "../CStdInt.h" #include "../Uncopyable.h" #include "../intrusive/List.h" #include "../threads/SharedData.h" diff --git a/src/beast/beast/utility/StaticObject.h b/src/beast/beast/utility/StaticObject.h index 30ab11cb9d..15fae2d255 100644 --- a/src/beast/beast/utility/StaticObject.h +++ b/src/beast/beast/utility/StaticObject.h @@ -98,7 +98,7 @@ private: static StaticData& get () { - static uint8 storage [sizeof (StaticData)]; + static std::uint8_t storage [sizeof (StaticData)]; return *(reinterpret_cast (&storage [0])); } diff --git a/src/beast/beast/utility/Utility.cpp b/src/beast/beast/utility/Utility.cpp index ef14dce0d9..e9b8f16929 100644 --- a/src/beast/beast/utility/Utility.cpp +++ b/src/beast/beast/utility/Utility.cpp @@ -23,9 +23,6 @@ #include "impl/Error.cpp" -// For Journal and Debug -#include "../../modules/beast_core/beast_core.h" - #include "impl/Debug.cpp" #include "impl/Journal.cpp" #include "impl/LeakChecked.cpp" diff --git a/src/beast/beast/utility/impl/Debug.cpp b/src/beast/beast/utility/impl/Debug.cpp index 8448e1888e..0e27385e32 100644 --- a/src/beast/beast/utility/impl/Debug.cpp +++ b/src/beast/beast/utility/impl/Debug.cpp @@ -19,6 +19,7 @@ #include "../Debug.h" #include "../../unit_test/suite.h" +#include "../../../modules/beast_core/system/SystemStats.h" namespace beast { diff --git a/src/beast/beast/utility/impl/Journal.cpp b/src/beast/beast/utility/impl/Journal.cpp index 42dd56273a..932ae6b752 100644 --- a/src/beast/beast/utility/impl/Journal.cpp +++ b/src/beast/beast/utility/impl/Journal.cpp @@ -18,6 +18,7 @@ //============================================================================== #include "../Journal.h" +#include "../../../modules/beast_core/memory/SharedSingleton.h" namespace beast { diff --git a/src/beast/beast/utility/impl/LeakChecked.cpp b/src/beast/beast/utility/impl/LeakChecked.cpp index df261e4908..3ac4e52040 100644 --- a/src/beast/beast/utility/impl/LeakChecked.cpp +++ b/src/beast/beast/utility/impl/LeakChecked.cpp @@ -18,6 +18,7 @@ //============================================================================== #include "../LeakChecked.h" +#include "../../../modules/beast_core/logging/Logger.h" namespace beast { diff --git a/src/beast/modules/beast_asio/basics/FixedInputBuffer.h b/src/beast/modules/beast_asio/basics/FixedInputBuffer.h index 12346875ee..96dbca2bb3 100644 --- a/src/beast/modules/beast_asio/basics/FixedInputBuffer.h +++ b/src/beast/modules/beast_asio/basics/FixedInputBuffer.h @@ -35,13 +35,13 @@ class FixedInputBuffer protected: struct CtorParams { - CtorParams (uint8 const* begin_, std::size_t bytes_) + CtorParams (std::uint8_t const* begin_, std::size_t bytes_) : begin (begin_) , bytes (bytes_) { } - uint8 const* begin; + std::uint8_t const* begin; std::size_t bytes; }; @@ -107,7 +107,7 @@ public: return read_impl (sizeof (T), t) != nullptr; } - uint8 operator[] (std::size_t index) const noexcept + std::uint8_t operator[] (std::size_t index) const noexcept { bassert (index >= 0 && index < size ()); return m_iter [index]; @@ -153,9 +153,9 @@ protected: } private: - uint8 const* m_begin; - uint8 const* m_iter; - uint8 const* m_end; + std::uint8_t const* m_begin; + std::uint8_t const* m_iter; + std::uint8_t const* m_end; }; //------------------------------------------------------------------------------ @@ -170,7 +170,7 @@ protected: SizedCtorParams (ConstBufferSequence const& buffers, Storage& storage) { boost::asio::mutable_buffer buffer (boost::asio::buffer (storage)); - data = boost::asio::buffer_cast (buffer); + data = boost::asio::buffer_cast (buffer); bytes = boost::asio::buffer_copy (buffer, buffers); } @@ -179,7 +179,7 @@ protected: return CtorParams (data, bytes); } - uint8 const* data; + std::uint8_t const* data; std::size_t bytes; }; @@ -191,7 +191,7 @@ public: } private: - boost::array m_storage; + boost::array m_storage; boost::asio::mutable_buffer m_buffer; }; diff --git a/src/beast/modules/beast_asio/http/HTTPClientType.cpp b/src/beast/modules/beast_asio/http/HTTPClientType.cpp index dae2052d5e..454976bf5f 100644 --- a/src/beast/modules/beast_asio/http/HTTPClientType.cpp +++ b/src/beast/modules/beast_asio/http/HTTPClientType.cpp @@ -21,6 +21,8 @@ #include "../../../beast/asio/placeholders.h" #include "../../../beast/unit_test/suite.h" +#include "../../../beast/cxx14/memory.h" // + namespace beast { namespace asio { @@ -190,7 +192,7 @@ public: String m_get_string; WaitableEvent m_done; - ScopedPointer m_stream; + std::unique_ptr m_stream; struct State { @@ -387,7 +389,8 @@ public: if (m_url.scheme () == "https") { typedef boost::asio::ssl::stream ssl_stream; - m_stream = new socket_wrapper (m_socket, m_context); + m_stream = std::make_unique < + socket_wrapper > (m_socket, m_context); /* m_stream->set_verify_mode ( boost::asio::ssl::verify_peer | @@ -399,7 +402,7 @@ public: return; } - m_stream = new socket_wrapper (m_socket); + m_stream = std::make_unique > (m_socket); handle_handshake (ec); } @@ -637,7 +640,7 @@ public: void testSync (String const& s, double timeoutSeconds) { - ScopedPointer client ( + std::unique_ptr client ( HTTPClientBase::New (Journal(), timeoutSeconds)); HTTPClientBase::result_type const& result ( @@ -649,7 +652,7 @@ public: void testAsync (String const& s, double timeoutSeconds) { IoServiceThread t; - ScopedPointer client ( + std::unique_ptr client ( HTTPClientBase::New (Journal(), timeoutSeconds)); client->async_get (t.get_io_service (), ParsedURL (s).url (), diff --git a/src/beast/modules/beast_asio/http/HTTPParser.h b/src/beast/modules/beast_asio/http/HTTPParser.h index 4295310616..3d559e66a4 100644 --- a/src/beast/modules/beast_asio/http/HTTPParser.h +++ b/src/beast/modules/beast_asio/http/HTTPParser.h @@ -79,7 +79,7 @@ public: protected: Type m_type; - ScopedPointer m_impl; + std::unique_ptr m_impl; SharedPtr m_request; SharedPtr m_response; }; diff --git a/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicPROXY.h b/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicPROXY.h index 43fe59dc41..423a6c5d4f 100644 --- a/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicPROXY.h +++ b/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicPROXY.h @@ -50,8 +50,8 @@ public: IPv4Address sourceAddress; IPv4Address destAddress; - uint16 sourcePort; - uint16 destPort; + std::uint16_t sourcePort; + std::uint16_t destPort; }; explicit HandshakeDetectLogicPROXY (arg_type const&) diff --git a/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicSSL2.h b/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicSSL2.h index 76f18f258d..1419242032 100644 --- a/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicSSL2.h +++ b/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicSSL2.h @@ -27,14 +27,14 @@ namespace asio { // // http://tools.ietf.org/html/rfc5246#appendix-E.2 // -// uint8 V2CipherSpec[3]; +// std::uint8_t V2CipherSpec[3]; // struct { -// uint16 msg_length; -// uint8 msg_type; +// std::uint16_t msg_length; +// std::uint8_t msg_type; // Version version; Should be 'ProtocolVersion'? -// uint16 cipher_spec_length; -// uint16 session_id_length; -// uint16 challenge_length; +// std::uint16_t cipher_spec_length; +// std::uint16_t session_id_length; +// std::uint16_t challenge_length; // ... // class HandshakeDetectLogicSSL2 : public HandshakeDetectLogic @@ -67,7 +67,7 @@ public: FixedInputBufferSize in (buffer); { - uint8 byte; + std::uint8_t byte; if (! in.peek (&byte)) return; @@ -80,7 +80,7 @@ public: // The remaining bits contain the // length of the following data in bytes. // - uint16 msg_length; + std::uint16_t msg_length; if (! in.readNetworkInteger(&msg_length)) return; @@ -95,7 +95,7 @@ public: if (msg_length < 9) return fail (); - uint8 msg_type; + std::uint8_t msg_type; if (! in.read (&msg_type)) return; diff --git a/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicSSL3.h b/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicSSL3.h index 721b2fe163..d77bed1edf 100644 --- a/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicSSL3.h +++ b/src/beast/modules/beast_asio/protocol/HandshakeDetectLogicSSL3.h @@ -56,10 +56,10 @@ public: template void analyze (ConstBufferSequence const& buffer) { - uint16 version; + std::uint16_t version; FixedInputBufferSize in (buffer); - uint8 msg_type; + std::uint8_t msg_type; if (! in.read (&msg_type)) return; @@ -72,7 +72,7 @@ public: return; version = fromNetworkByteOrder (version); - uint16 length; + std::uint16_t length; if (! in.read (&length)) return; diff --git a/src/beast/modules/beast_asio/protocol/InputParser.h b/src/beast/modules/beast_asio/protocol/InputParser.h index 97962b7ef3..f9314d9880 100644 --- a/src/beast/modules/beast_asio/protocol/InputParser.h +++ b/src/beast/modules/beast_asio/protocol/InputParser.h @@ -230,7 +230,7 @@ struct Get // An unsigned 32 bit number expressed as a string struct UInt32Str { - uint32 value; + std::uint32_t value; }; template <> @@ -239,7 +239,7 @@ struct Get static State func (Input in, UInt32Str& t) { State state; - uint32 value (0); + std::uint32_t value (0); Digit digit; // have to have at least one digit @@ -266,7 +266,7 @@ struct Get if (value == 0) return State::fail; - uint32 newValue = (value * 10) + digit.value; + std::uint32_t newValue = (value * 10) + digit.value; // overflow if (newValue < value) @@ -284,7 +284,7 @@ struct Get // An unsigned 16 bit number expressed as a string struct UInt16Str { - uint16 value; + std::uint16_t value; }; template <> @@ -298,7 +298,7 @@ struct Get { if (v.value <= 65535) { - t.value = uint16(v.value); + t.value = std::uint16_t(v.value); return State::pass; } return State::fail; @@ -312,7 +312,7 @@ struct Get // An unsigned 8 bit number expressed as a string struct UInt8Str { - uint8 value; + std::uint8_t value; }; template <> @@ -326,7 +326,7 @@ struct Get { if (v.value <= 255) { - t.value = uint8(v.value); + t.value = std::uint8_t(v.value); return State::pass; } return State::fail; @@ -340,7 +340,7 @@ struct Get // An dotted IPv4 address struct IPv4Address { - uint8 value [4]; + std::uint8_t value [4]; String toString () const { diff --git a/src/beast/modules/beast_core/beast_core.cpp b/src/beast/modules/beast_core/beast_core.cpp index 07f0e1ded3..6c2c4cb7ef 100644 --- a/src/beast/modules/beast_core/beast_core.cpp +++ b/src/beast/modules/beast_core/beast_core.cpp @@ -157,18 +157,12 @@ #include "text/StringArray.cpp" #include "text/StringPairArray.cpp" -#include "thread/impl/TrackedMutex.cpp" #include "thread/DeadlineTimer.cpp" #include "thread/Workers.cpp" -#include "threads/ChildProcess.cpp" - #include "time/AtExitHook.cpp" #include "time/Time.cpp" -#include "xml/XmlDocument.cpp" -#include "xml/XmlElement.cpp" - #if BEAST_MAC || BEAST_IOS #include "native/osx_ObjCHelpers.h" #endif @@ -183,7 +177,6 @@ #if BEAST_MAC || BEAST_IOS #include "native/mac_Files.mm" -#include "native/mac_Network.mm" #include "native/mac_Strings.mm" #include "native/mac_SystemStats.mm" #include "native/mac_Threads.mm" @@ -191,34 +184,28 @@ #elif BEAST_WINDOWS #include "native/win32_ComSmartPtr.h" #include "native/win32_Files.cpp" -#include "native/win32_Network.cpp" #include "native/win32_Registry.cpp" #include "native/win32_SystemStats.cpp" #include "native/win32_Threads.cpp" #elif BEAST_LINUX #include "native/linux_Files.cpp" -#include "native/linux_Network.cpp" #include "native/linux_SystemStats.cpp" #include "native/linux_Threads.cpp" #elif BEAST_BSD #include "native/bsd_Files.cpp" -#include "native/bsd_Network.cpp" #include "native/bsd_SystemStats.cpp" #include "native/bsd_Threads.cpp" #elif BEAST_ANDROID #include "native/android_Files.cpp" #include "native/android_Misc.cpp" -#include "native/android_Network.cpp" #include "native/android_SystemStats.cpp" #include "native/android_Threads.cpp" #endif -#include "threads/HighResolutionTimer.cpp" - // Has to be outside the beast namespace extern "C" { void beast_reportFatalError (char const* message, char const* fileName, int lineNumber) diff --git a/src/beast/modules/beast_core/beast_core.h b/src/beast/modules/beast_core/beast_core.h index 26776e882d..ea57ea6a61 100644 --- a/src/beast/modules/beast_core/beast_core.h +++ b/src/beast/modules/beast_core/beast_core.h @@ -44,7 +44,6 @@ //------------------------------------------------------------------------------ // New header-only library modeled more closely according to boost -#include "../../beast/CStdInt.h" #include "../../beast/SmartPtr.h" #include "../../beast/StaticAssert.h" #include "../../beast/Uncopyable.h" @@ -74,12 +73,11 @@ class OutputStream; class FileInputStream; class FileOutputStream; -} // namespace beast +} // beast // Order matters, since headers don't have their own #include lines. // Add new includes to the bottom. -#include "diagnostic/Throw.h" #include "system/Functional.h" #include "time/AtExitHook.h" @@ -143,14 +141,12 @@ class FileOutputStream; #include "files/File.h" #include "thread/MutexTraits.h" -#include "thread/TrackedMutex.h" #include "diagnostic/FatalError.h" #include "text/LexicalCast.h" #include "maths/Math.h" #include "logging/Logger.h" #include "containers/LinkedListPointer.h" #include "maths/Random.h" -#include "containers/OwnedArray.h" #include "text/StringPairArray.h" #include "containers/ScopedValueSetter.h" #include "maths/Range.h" @@ -171,13 +167,8 @@ class FileOutputStream; #include "system/SystemStats.h" #include "diagnostic/SemanticVersion.h" -#include "threads/ChildProcess.h" #include "threads/DynamicLibrary.h" -#include "threads/HighResolutionTimer.h" -#include "threads/InterProcessLock.h" #include "threads/Process.h" -#include "xml/XmlDocument.h" -#include "xml/XmlElement.h" #include "diagnostic/UnitTestUtilities.h" #include "diagnostic/MeasureFunctionCallTime.h" diff --git a/src/beast/modules/beast_core/containers/Array.h b/src/beast/modules/beast_core/containers/Array.h index d516cbfd2d..fb66292f29 100644 --- a/src/beast/modules/beast_core/containers/Array.h +++ b/src/beast/modules/beast_core/containers/Array.h @@ -24,8 +24,11 @@ #ifndef BEAST_ARRAY_H_INCLUDED #define BEAST_ARRAY_H_INCLUDED -namespace beast -{ +#include "ArrayAllocationBase.h" +#include "ElementComparator.h" +#include "../threads/CriticalSection.h" + +namespace beast { //============================================================================== /** @@ -39,17 +42,13 @@ namespace beast - it must be able to be relocated in memory by a memcpy without this causing any problems - so objects whose functionality relies on external pointers or references to themselves can be used. - You can of course have an array of pointers to any kind of object, e.g. Array , but if - you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the - SharedObjectArray class for more powerful ways of holding lists of objects. - For holding lists of strings, you can use Array\, but it's usually better to use the specialised class StringArray, which provides more useful functions. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection. - @see OwnedArray, SharedObjectArray, StringArray, CriticalSection + @see SharedObjectArray, StringArray, CriticalSection */ template class ArrayAllocationBase @@ -129,6 +130,6 @@ public: int numAllocated; }; -} // namespace beast +} // beast #endif // BEAST_ARRAYALLOCATIONBASE_H_INCLUDED diff --git a/src/beast/modules/beast_core/containers/ElementComparator.h b/src/beast/modules/beast_core/containers/ElementComparator.h index 929e71ca71..d856ab879c 100644 --- a/src/beast/modules/beast_core/containers/ElementComparator.h +++ b/src/beast/modules/beast_core/containers/ElementComparator.h @@ -179,7 +179,7 @@ template class DefaultElementComparator { private: - typedef PARAMETER_TYPE (ElementType) ParameterType; + typedef ElementType ParameterType; public: static int compareElements (ParameterType first, ParameterType second) @@ -188,7 +188,7 @@ public: } }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/containers/LinkedListPointer.h b/src/beast/modules/beast_core/containers/LinkedListPointer.h index 4ab1aca684..046434ddc4 100644 --- a/src/beast/modules/beast_core/containers/LinkedListPointer.h +++ b/src/beast/modules/beast_core/containers/LinkedListPointer.h @@ -360,6 +360,6 @@ private: ObjectType* item; }; -} // namespace beast +} // beast #endif // BEAST_LINKEDLISTPOINTER_H_INCLUDED diff --git a/src/beast/modules/beast_core/containers/OwnedArray.h b/src/beast/modules/beast_core/containers/OwnedArray.h deleted file mode 100644 index b971690dae..0000000000 --- a/src/beast/modules/beast_core/containers/OwnedArray.h +++ /dev/null @@ -1,893 +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_OWNEDARRAY_H_INCLUDED -#define BEAST_OWNEDARRAY_H_INCLUDED - -namespace beast -{ - -//============================================================================== -/** An array designed for holding objects. - - This holds a list of pointers to objects, and will automatically - delete the objects when they are removed from the array, or when the - array is itself deleted. - - Declare it in the form: OwnedArray - - ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass()); - - After adding objects, they are 'owned' by the array and will be deleted when - removed or replaced. - - To make all the array's methods thread-safe, pass in "CriticalSection" as the templated - TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection. - - @see Array, SharedObjectArray, StringArray, CriticalSection -*/ -template - -class OwnedArray - : LeakChecked > - , public Uncopyable -{ -public: - //============================================================================== - /** Creates an empty array. */ - OwnedArray() noexcept - : numUsed (0) - { - } - - /** Deletes the array and also deletes any objects inside it. - - To get rid of the array without deleting its objects, use its - clear (false) method before deleting it. - */ - ~OwnedArray() - { - deleteAllObjects(); - } - - #if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS - OwnedArray (OwnedArray&& other) noexcept - : data (static_cast &&> (other.data)), - numUsed (other.numUsed) - { - other.numUsed = 0; - } - - OwnedArray& operator= (OwnedArray&& other) noexcept - { - const ScopedLockType lock (getLock()); - deleteAllObjects(); - - data = static_cast &&> (other.data); - numUsed = other.numUsed; - other.numUsed = 0; - return *this; - } - #endif - - //============================================================================== - /** Clears the array, optionally deleting the objects inside it first. */ - void clear (bool deleteObjects = true) - { - const ScopedLockType lock (getLock()); - - if (deleteObjects) - deleteAllObjects(); - - data.setAllocatedSize (0); - numUsed = 0; - } - - /** Clears the array, optionally deleting the objects inside it first. - - The array's allocated storage is preserved. - - @see clear - */ - void clearQuick(bool deleteObjects = true) - { - const ScopedLockType lock (getLock()); - - if (deleteObjects) - deleteAllObjects(); - - numUsed = 0; - } - - //============================================================================== - /** Returns the number of items currently in the array. - @see operator[] - */ - inline int size() const noexcept - { - return numUsed; - } - - /** Returns a pointer to the object at this index in the array. - - If the index is out-of-range, this will return a null pointer, (and - it could be null anyway, because it's ok for the array to hold null - pointers as well as objects). - - @see getUnchecked - */ - inline ObjectClass* operator[] (const int index) const noexcept - { - const ScopedLockType lock (getLock()); - if (isPositiveAndBelow (index, numUsed)) - { - bassert (data.elements != nullptr); - return data.elements [index]; - } - - return nullptr; - } - - /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range. - - This is a faster and less safe version of operator[] which doesn't check the index passed in, so - it can be used when you're sure the index is always going to be legal. - */ - inline ObjectClass* getUnchecked (const int index) const noexcept - { - const ScopedLockType lock (getLock()); - bassert (isPositiveAndBelow (index, numUsed) && data.elements != nullptr); - return data.elements [index]; - } - - /** Returns a pointer to the first object in the array. - - This will return a null pointer if the array's empty. - @see getLast - */ - inline ObjectClass* getFirst() const noexcept - { - const ScopedLockType lock (getLock()); - return numUsed > 0 ? data.elements [0] - : static_cast (nullptr); - } - - /** Returns a pointer to the last object in the array. - - This will return a null pointer if the array's empty. - @see getFirst - */ - inline ObjectClass* getLast() const noexcept - { - const ScopedLockType lock (getLock()); - return numUsed > 0 ? data.elements [numUsed - 1] - : static_cast (nullptr); - } - - /** Returns a pointer to the actual array data. - This pointer will only be valid until the next time a non-const method - is called on the array. - */ - inline ObjectClass** getRawDataPointer() noexcept - { - return data.elements; - } - - //============================================================================== - /** Returns a pointer to the first element in the array. - This method is provided for compatibility with standard C++ iteration mechanisms. - */ - inline ObjectClass** begin() const noexcept - { - return data.elements; - } - - /** Returns a pointer to the element which follows the last element in the array. - This method is provided for compatibility with standard C++ iteration mechanisms. - */ - inline ObjectClass** end() const noexcept - { - return data.elements + numUsed; - } - - //============================================================================== - /** Finds the index of an object which might be in the array. - - @param objectToLookFor the object to look for - @returns the index at which the object was found, or -1 if it's not found - */ - int indexOf (const ObjectClass* const objectToLookFor) const noexcept - { - const ScopedLockType lock (getLock()); - ObjectClass* const* e = data.elements.getData(); - ObjectClass* const* const end_ = e + numUsed; - - for (; e != end_; ++e) - if (objectToLookFor == *e) - return static_cast (e - data.elements.getData()); - - return -1; - } - - /** Returns true if the array contains a specified object. - - @param objectToLookFor the object to look for - @returns true if the object is in the array - */ - bool contains (const ObjectClass* const objectToLookFor) const noexcept - { - const ScopedLockType lock (getLock()); - ObjectClass* const* e = data.elements.getData(); - ObjectClass* const* const end_ = e + numUsed; - - for (; e != end_; ++e) - if (objectToLookFor == *e) - return true; - - return false; - } - - //============================================================================== - /** Appends a new object to the end of the array. - - Note that the this object will be deleted by the OwnedArray when it - is removed, so be careful not to delete it somewhere else. - - Also be careful not to add the same object to the array more than once, - as this will obviously cause deletion of dangling pointers. - - @param newObject the new object to add to the array - @see set, insert, addIfNotAlreadyThere, addSorted - */ - ObjectClass* add (ObjectClass* const newObject) noexcept - { - const ScopedLockType lock (getLock()); - data.ensureAllocatedSize (numUsed + 1); - bassert (data.elements != nullptr); - data.elements [numUsed++] = const_cast (newObject); - return const_cast (newObject); - } - - /** Inserts a new object into the array at the given index. - - Note that the this object will be deleted by the OwnedArray when it - is removed, so be careful not to delete it somewhere else. - - If the index is less than 0 or greater than the size of the array, the - element will be added to the end of the array. - Otherwise, it will be inserted into the array, moving all the later elements - along to make room. - - Be careful not to add the same object to the array more than once, - as this will obviously cause deletion of dangling pointers. - - @param indexToInsertAt the index at which the new element should be inserted - @param newObject the new object to add to the array - @see add, addSorted, addIfNotAlreadyThere, set - */ - void insert (int indexToInsertAt, - ObjectClass* const newObject) noexcept - { - if (indexToInsertAt >= 0) - { - const ScopedLockType lock (getLock()); - - if (indexToInsertAt > numUsed) - indexToInsertAt = numUsed; - - data.ensureAllocatedSize (numUsed + 1); - bassert (data.elements != nullptr); - - ObjectClass** const e = data.elements + indexToInsertAt; - const int numToMove = numUsed - indexToInsertAt; - - if (numToMove > 0) - memmove (e + 1, e, sizeof (ObjectClass*) * (size_t) numToMove); - - *e = const_cast (newObject); - ++numUsed; - } - else - { - add (newObject); - } - } - - /** Inserts an array of values into this array at a given position. - - If the index is less than 0 or greater than the size of the array, the - new elements will be added to the end of the array. - Otherwise, they will be inserted into the array, moving all the later elements - along to make room. - - @param indexToInsertAt the index at which the first new element should be inserted - @param newObjects the new values to add to the array - @param numberOfElements how many items are in the array - @see insert, add, addSorted, set - */ - void insertArray (int indexToInsertAt, - ObjectClass* const* newObjects, - int numberOfElements) - { - if (numberOfElements > 0) - { - const ScopedLockType lock (getLock()); - data.ensureAllocatedSize (numUsed + numberOfElements); - ObjectClass** insertPos = data.elements; - - if (isPositiveAndBelow (indexToInsertAt, numUsed)) - { - insertPos += indexToInsertAt; - const size_t numberToMove = (size_t) (numUsed - indexToInsertAt); - memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ObjectClass*)); - } - else - { - insertPos += numUsed; - } - - numUsed += numberOfElements; - - while (--numberOfElements >= 0) - *insertPos++ = *newObjects++; - } - } - - /** Appends a new object at the end of the array as long as the array doesn't - already contain it. - - If the array already contains a matching object, nothing will be done. - - @param newObject the new object to add to the array - */ - void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept - { - const ScopedLockType lock (getLock()); - - if (! contains (newObject)) - add (newObject); - } - - /** Replaces an object in the array with a different one. - - If the index is less than zero, this method does nothing. - If the index is beyond the end of the array, the new object is added to the end of the array. - - Be careful not to add the same object to the array more than once, - as this will obviously cause deletion of dangling pointers. - - @param indexToChange the index whose value you want to change - @param newObject the new value to set for this index. - @param deleteOldElement whether to delete the object that's being replaced with the new one - @see add, insert, remove - */ - void set (const int indexToChange, - const ObjectClass* const newObject, - const bool deleteOldElement = true) - { - if (indexToChange >= 0) - { - ObjectClass* toDelete = nullptr; - - { - const ScopedLockType lock (getLock()); - - if (indexToChange < numUsed) - { - if (deleteOldElement) - { - toDelete = data.elements [indexToChange]; - - if (toDelete == newObject) - toDelete = nullptr; - } - - data.elements [indexToChange] = const_cast (newObject); - } - else - { - data.ensureAllocatedSize (numUsed + 1); - data.elements [numUsed++] = const_cast (newObject); - } - } - - // don't want to use a ScopedPointer here because if the - // object has a private destructor, both OwnedArray and - // ScopedPointer would need to be friend classes.. - ContainerDeletePolicy ::destroy (toDelete); - } - else - { - bassertfalse; // you're trying to set an object at a negative index, which doesn't have - // any effect - but since the object is not being added, it may be leaking.. - } - } - - /** Adds elements from another array to the end of this array. - - @param arrayToAddFrom the array from which to copy the elements - @param startIndex the first element of the other array to start copying from - @param numElementsToAdd how many elements to add from the other array. If this - value is negative or greater than the number of available elements, - all available elements will be copied. - @see add - */ - template - void addArray (const OtherArrayType& arrayToAddFrom, - int startIndex = 0, - int numElementsToAdd = -1) - { - const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock()); - const ScopedLockType lock2 (getLock()); - - if (startIndex < 0) - { - bassertfalse; - startIndex = 0; - } - - if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size()) - numElementsToAdd = arrayToAddFrom.size() - startIndex; - - data.ensureAllocatedSize (numUsed + numElementsToAdd); - bassert (numElementsToAdd <= 0 || data.elements != nullptr); - - while (--numElementsToAdd >= 0) - { - data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++); - ++numUsed; - } - } - - /** Adds copies of the elements in another array to the end of this array. - - The other array must be either an OwnedArray of a compatible type of object, or an Array - containing pointers to the same kind of object. The objects involved must provide - a copy constructor, and this will be used to create new copies of each element, and - add them to this array. - - @param arrayToAddFrom the array from which to copy the elements - @param startIndex the first element of the other array to start copying from - @param numElementsToAdd how many elements to add from the other array. If this - value is negative or greater than the number of available elements, - all available elements will be copied. - @see add - */ - template - void addCopiesOf (const OtherArrayType& arrayToAddFrom, - int startIndex = 0, - int numElementsToAdd = -1) - { - const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock()); - const ScopedLockType lock2 (getLock()); - - if (startIndex < 0) - { - bassertfalse; - startIndex = 0; - } - - if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size()) - numElementsToAdd = arrayToAddFrom.size() - startIndex; - - data.ensureAllocatedSize (numUsed + numElementsToAdd); - bassert (numElementsToAdd <= 0 || data.elements != nullptr); - - while (--numElementsToAdd >= 0) - { - data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++)); - ++numUsed; - } - } - - /** Inserts a new object into the array assuming that the array is sorted. - - This will use a comparator to find the position at which the new object - should go. If the array isn't sorted, the behaviour of this - method will be unpredictable. - - @param comparator the comparator to use to compare the elements - see the sort method - for details about this object's structure - @param newObject the new object to insert to the array - @returns the index at which the new object was added - @see add, sort, indexOfSorted - */ - template - int addSorted (ElementComparator& comparator, ObjectClass* const newObject) noexcept - { - (void) comparator; // if you pass in an object with a static compareElements() method, this - // avoids getting warning messages about the parameter being unused - const ScopedLockType lock (getLock()); - const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed); - insert (index, newObject); - return index; - } - - /** Finds the index of an object in the array, assuming that the array is sorted. - - This will use a comparator to do a binary-chop to find the index of the given - element, if it exists. If the array isn't sorted, the behaviour of this - method will be unpredictable. - - @param comparator the comparator to use to compare the elements - see the sort() - method for details about the form this object should take - @param objectToLookFor the object to search for - @returns the index of the element, or -1 if it's not found - @see addSorted, sort - */ - template - int indexOfSorted (ElementComparator& comparator, const ObjectClass* const objectToLookFor) const noexcept - { - (void) comparator; - const ScopedLockType lock (getLock()); - int s = 0, e = numUsed; - - while (s < e) - { - if (comparator.compareElements (objectToLookFor, data.elements [s]) == 0) - return s; - - const int halfway = (s + e) / 2; - if (halfway == s) - break; - - if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0) - s = halfway; - else - e = halfway; - } - - return -1; - } - - //============================================================================== - /** Removes an object from the array. - - This will remove the object at a given index (optionally also - deleting it) and move back all the subsequent objects to close the gap. - If the index passed in is out-of-range, nothing will happen. - - @param indexToRemove the index of the element to remove - @param deleteObject whether to delete the object that is removed - @see removeObject, removeRange - */ - void remove (const int indexToRemove, - const bool deleteObject = true) - { - ObjectClass* toDelete = nullptr; - - { - const ScopedLockType lock (getLock()); - - if (isPositiveAndBelow (indexToRemove, numUsed)) - { - ObjectClass** const e = data.elements + indexToRemove; - - if (deleteObject) - toDelete = *e; - - --numUsed; - const int numToShift = numUsed - indexToRemove; - - if (numToShift > 0) - memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numToShift); - } - } - - // don't want to use a ScopedPointer here because if the - // object has a private destructor, both OwnedArray and - // ScopedPointer would need to be friend classes.. - ContainerDeletePolicy ::destroy (toDelete); - - if ((numUsed << 1) < data.numAllocated) - minimiseStorageOverheads(); - } - - /** Removes and returns an object from the array without deleting it. - - This will remove the object at a given index and return it, moving back all - the subsequent objects to close the gap. If the index passed in is out-of-range, - nothing will happen. - - @param indexToRemove the index of the element to remove - @see remove, removeObject, removeRange - */ - ObjectClass* removeAndReturn (const int indexToRemove) - { - ObjectClass* removedItem = nullptr; - const ScopedLockType lock (getLock()); - - if (isPositiveAndBelow (indexToRemove, numUsed)) - { - ObjectClass** const e = data.elements + indexToRemove; - removedItem = *e; - - --numUsed; - const int numToShift = numUsed - indexToRemove; - - if (numToShift > 0) - memmove (e, e + 1, sizeof (ObjectClass*) * (size_t) numToShift); - - if ((numUsed << 1) < data.numAllocated) - minimiseStorageOverheads(); - } - - return removedItem; - } - - /** Removes a specified object from the array. - - If the item isn't found, no action is taken. - - @param objectToRemove the object to try to remove - @param deleteObject whether to delete the object (if it's found) - @see remove, removeRange - */ - void removeObject (const ObjectClass* const objectToRemove, - const bool deleteObject = true) - { - const ScopedLockType lock (getLock()); - ObjectClass** const e = data.elements.getData(); - - for (int i = 0; i < numUsed; ++i) - { - if (objectToRemove == e[i]) - { - remove (i, deleteObject); - break; - } - } - } - - /** Removes a range of objects from the array. - - This will remove a set of objects, starting from the given index, - and move any subsequent elements down to close the gap. - - If the range extends beyond the bounds of the array, it will - be safely clipped to the size of the array. - - @param startIndex the index of the first object to remove - @param numberToRemove how many objects should be removed - @param deleteObjects whether to delete the objects that get removed - @see remove, removeObject - */ - void removeRange (int startIndex, - const int numberToRemove, - const bool deleteObjects = true) - { - const ScopedLockType lock (getLock()); - const int endIndex = blimit (0, numUsed, startIndex + numberToRemove); - startIndex = blimit (0, numUsed, startIndex); - - if (endIndex > startIndex) - { - if (deleteObjects) - { - for (int i = startIndex; i < endIndex; ++i) - { - ContainerDeletePolicy ::destroy (data.elements [i]); - data.elements [i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer) - } - } - - const int rangeSize = endIndex - startIndex; - ObjectClass** e = data.elements + startIndex; - int numToShift = numUsed - endIndex; - numUsed -= rangeSize; - - while (--numToShift >= 0) - { - *e = e [rangeSize]; - ++e; - } - - if ((numUsed << 1) < data.numAllocated) - minimiseStorageOverheads(); - } - } - - /** Removes the last n objects from the array. - - @param howManyToRemove how many objects to remove from the end of the array - @param deleteObjects whether to also delete the objects that are removed - @see remove, removeObject, removeRange - */ - void removeLast (int howManyToRemove = 1, - const bool deleteObjects = true) - { - const ScopedLockType lock (getLock()); - - if (howManyToRemove >= numUsed) - clear (deleteObjects); - else - removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects); - } - - /** Swaps a pair of objects in the array. - - If either of the indexes passed in is out-of-range, nothing will happen, - otherwise the two objects at these positions will be exchanged. - */ - void swap (const int index1, - const int index2) noexcept - { - const ScopedLockType lock (getLock()); - - if (isPositiveAndBelow (index1, numUsed) - && isPositiveAndBelow (index2, numUsed)) - { - std::swap (data.elements [index1], - data.elements [index2]); - } - } - - /** Moves one of the objects to a different position. - - This will move the object to a specified index, shuffling along - any intervening elements as required. - - So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling - move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }. - - @param currentIndex the index of the object to be moved. If this isn't a - valid index, then nothing will be done - @param newIndex the index at which you'd like this object to end up. If this - is less than zero, it will be moved to the end of the array - */ - void move (const int currentIndex, - int newIndex) noexcept - { - if (currentIndex != newIndex) - { - const ScopedLockType lock (getLock()); - - if (isPositiveAndBelow (currentIndex, numUsed)) - { - if (! isPositiveAndBelow (newIndex, numUsed)) - newIndex = numUsed - 1; - - ObjectClass* const value = data.elements [currentIndex]; - - if (newIndex > currentIndex) - { - memmove (data.elements + currentIndex, - data.elements + currentIndex + 1, - sizeof (ObjectClass*) * (size_t) (newIndex - currentIndex)); - } - else - { - memmove (data.elements + newIndex + 1, - data.elements + newIndex, - sizeof (ObjectClass*) * (size_t) (currentIndex - newIndex)); - } - - data.elements [newIndex] = value; - } - } - } - - /** This swaps the contents of this array with those of another array. - - If you need to exchange two arrays, this is vastly quicker than using copy-by-value - because it just swaps their internal pointers. - */ - template - void swapWith (OtherArrayType& otherArray) noexcept - { - const ScopedLockType lock1 (getLock()); - const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock()); - - data.swapWith (otherArray.data); - std::swap (numUsed, otherArray.numUsed); - } - - //============================================================================== - /** Reduces the amount of storage being used by the array. - - Arrays typically allocate slightly more storage than they need, and after - removing elements, they may have quite a lot of unused space allocated. - This method will reduce the amount of allocated storage to a minimum. - */ - void minimiseStorageOverheads() noexcept - { - const ScopedLockType lock (getLock()); - data.shrinkToNoMoreThan (numUsed); - } - - /** Increases the array's internal storage to hold a minimum number of elements. - - Calling this before adding a large known number of elements means that - the array won't have to keep dynamically resizing itself as the elements - are added, and it'll therefore be more efficient. - */ - void ensureStorageAllocated (const int minNumElements) noexcept - { - const ScopedLockType lock (getLock()); - data.ensureAllocatedSize (minNumElements); - } - - //============================================================================== - /** Sorts the elements in the array. - - This will use a comparator object to sort the elements into order. The object - passed must have a method of the form: - @code - int compareElements (ElementType first, ElementType second); - @endcode - - ..and this method must return: - - a value of < 0 if the first comes before the second - - a value of 0 if the two objects are equivalent - - a value of > 0 if the second comes before the first - - To improve performance, the compareElements() method can be declared as static or const. - - @param comparator the comparator to use for comparing elements. - @param retainOrderOfEquivalentItems if this is true, then items - which the comparator says are equivalent will be - kept in the order in which they currently appear - in the array. This is slower to perform, but may - be important in some cases. If it's false, a faster - algorithm is used, but equivalent elements may be - rearranged. - @see sortArray, indexOfSorted - */ - template - void sort (ElementComparator& comparator, - const bool retainOrderOfEquivalentItems = false) const noexcept - { - (void) comparator; // if you pass in an object with a static compareElements() method, this - // avoids getting warning messages about the parameter being unused - - const ScopedLockType lock (getLock()); - sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems); - } - - //============================================================================== - /** Returns the CriticalSection that locks this array. - To lock, you can call getLock().enter() and getLock().exit(), or preferably use - an object of ScopedLockType as an RAII lock for it. - */ - inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; } - - /** Returns the type of scoped lock to use for locking this array */ - typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType; - - -private: - //============================================================================== - ArrayAllocationBase data; - int numUsed; - - void deleteAllObjects() - { - while (numUsed > 0) - ContainerDeletePolicy ::destroy (data.elements [--numUsed]); - } -}; - -} // namespace beast - -#endif diff --git a/src/beast/modules/beast_core/containers/ScopedValueSetter.h b/src/beast/modules/beast_core/containers/ScopedValueSetter.h index 3859b74921..254268769f 100644 --- a/src/beast/modules/beast_core/containers/ScopedValueSetter.h +++ b/src/beast/modules/beast_core/containers/ScopedValueSetter.h @@ -91,6 +91,6 @@ private: const ValueType originalValue; }; -} // namespace beast +} // beast #endif // BEAST_SCOPEDVALUESETTER_H_INCLUDED diff --git a/src/beast/modules/beast_core/diagnostic/FatalError.cpp b/src/beast/modules/beast_core/diagnostic/FatalError.cpp index 4585f62337..6be4f2ce4b 100644 --- a/src/beast/modules/beast_core/diagnostic/FatalError.cpp +++ b/src/beast/modules/beast_core/diagnostic/FatalError.cpp @@ -91,7 +91,7 @@ FatalError::FatalError (char const* message, char const* fileName, int lineNumbe static LockType s_mutex; - LockType::ScopedLockType lock (s_mutex); + std::lock_guard lock (s_mutex); String const backtraceString = SystemStats::getStackBacktrace (); diff --git a/src/beast/modules/beast_core/diagnostic/FatalError.h b/src/beast/modules/beast_core/diagnostic/FatalError.h index 5aa949d5b8..70e75adf21 100644 --- a/src/beast/modules/beast_core/diagnostic/FatalError.h +++ b/src/beast/modules/beast_core/diagnostic/FatalError.h @@ -149,6 +149,6 @@ private: static Reporter* s_reporter; }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/diagnostic/MeasureFunctionCallTime.h b/src/beast/modules/beast_core/diagnostic/MeasureFunctionCallTime.h index 41a05dbed9..c04b32d070 100644 --- a/src/beast/modules/beast_core/diagnostic/MeasureFunctionCallTime.h +++ b/src/beast/modules/beast_core/diagnostic/MeasureFunctionCallTime.h @@ -28,7 +28,7 @@ namespace beast template double measureFunctionCallTime (Function f) { - int64 const startTime (Time::getHighResolutionTicks ()); + std::int64_t const startTime (Time::getHighResolutionTicks ()); f (); return Time::highResolutionTicksToSeconds ( Time::getHighResolutionTicks () - startTime); @@ -40,7 +40,7 @@ template double measureFunctionCallTime (Function f, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) { - int64 const startTime (Time::getHighResolutionTicks ()); + std::int64_t const startTime (Time::getHighResolutionTicks ()); f (p1, p2, p3, p4, p5 ,p6 ,p7 ,p8); return Time::highResolutionTicksToSeconds ( Time::getHighResolutionTicks () - startTime); @@ -51,7 +51,7 @@ template double measureFunctionCallTime (Function f, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) { - int64 const startTime (Time::getHighResolutionTicks ()); + std::int64_t const startTime (Time::getHighResolutionTicks ()); f (p1, p2, p3, p4, p5 ,p6 ,p7 ,p8); return Time::highResolutionTicksToSeconds ( Time::getHighResolutionTicks () - startTime); @@ -62,7 +62,7 @@ template double measureFunctionCallTime (Function f, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) { - int64 const startTime (Time::getHighResolutionTicks ()); + std::int64_t const startTime (Time::getHighResolutionTicks ()); f (p1, p2, p3, p4, p5 ,p6 ,p7 ,p8); return Time::highResolutionTicksToSeconds ( Time::getHighResolutionTicks () - startTime); @@ -73,13 +73,13 @@ template double measureFunctionCallTime (Function f, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) { - int64 const startTime (Time::getHighResolutionTicks ()); + std::int64_t const startTime (Time::getHighResolutionTicks ()); f (p1, p2, p3, p4, p5 ,p6 ,p7 ,p8); return Time::highResolutionTicksToSeconds ( Time::getHighResolutionTicks () - startTime); } #endif -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/diagnostic/SemanticVersion.h b/src/beast/modules/beast_core/diagnostic/SemanticVersion.h index 691f9ff5d0..2e58a3fa61 100644 --- a/src/beast/modules/beast_core/diagnostic/SemanticVersion.h +++ b/src/beast/modules/beast_core/diagnostic/SemanticVersion.h @@ -30,7 +30,7 @@ namespace beast http://semver.org/ */ -class BEAST_API SemanticVersion +class SemanticVersion { public: int majorVersion; @@ -74,6 +74,6 @@ private: static bool chopIdentifiers (StringArray* value, bool preRelease, String& input); }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/diagnostic/Throw.h b/src/beast/modules/beast_core/diagnostic/Throw.h deleted file mode 100644 index bef8b256a6..0000000000 --- a/src/beast/modules/beast_core/diagnostic/Throw.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_THROW_H_INCLUDED -#define BEAST_THROW_H_INCLUDED - -namespace beast -{ - -/** Throw an exception, with a debugger hook. - - This provides an opportunity to utilize the debugger before - the stack is unwound. -*/ -namespace Debug -{ -extern void breakPoint (); -}; - -template -void Throw (Exception const& e, char const* = "", int = 0) -{ - throw e; -} - -} // namespace beast - -#endif diff --git a/src/beast/modules/beast_core/diagnostic/UnitTestUtilities.h b/src/beast/modules/beast_core/diagnostic/UnitTestUtilities.h index 1f226dce84..e8c78edb4c 100644 --- a/src/beast/modules/beast_core/diagnostic/UnitTestUtilities.h +++ b/src/beast/modules/beast_core/diagnostic/UnitTestUtilities.h @@ -36,7 +36,7 @@ void repeatableShuffle (int const numberOfItems, T& arrayOfItems, Random& r) } template -void repeatableShuffle (int const numberOfItems, T& arrayOfItems, int64 seedValue) +void repeatableShuffle (int const numberOfItems, T& arrayOfItems, std::int64_t seedValue) { Random r (seedValue); repeatableShuffle (numberOfItems, arrayOfItems, r); @@ -64,7 +64,7 @@ struct Payload @param maximumBytes The largest number of bytes in the resulting payload. @param seedValue The value to seed the random number generator with. */ - void repeatableRandomFill (int minimumBytes, int maximumBytes, int64 seedValue) noexcept + void repeatableRandomFill (int minimumBytes, int maximumBytes, std::int64_t seedValue) noexcept { bassert (minimumBytes >=0 && maximumBytes <= bufferSize); diff --git a/src/beast/modules/beast_core/files/DirectoryIterator.cpp b/src/beast/modules/beast_core/files/DirectoryIterator.cpp index 5195f20697..ead47f2507 100644 --- a/src/beast/modules/beast_core/files/DirectoryIterator.cpp +++ b/src/beast/modules/beast_core/files/DirectoryIterator.cpp @@ -68,7 +68,7 @@ bool DirectoryIterator::next() return next (nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); } -bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize, +bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { hasBeenAdvanced = true; @@ -156,4 +156,4 @@ float DirectoryIterator::getEstimatedProgress() const return detailedIndex / totalNumFiles; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/files/DirectoryIterator.h b/src/beast/modules/beast_core/files/DirectoryIterator.h index 62c43351ba..ebe168d2b8 100644 --- a/src/beast/modules/beast_core/files/DirectoryIterator.h +++ b/src/beast/modules/beast_core/files/DirectoryIterator.h @@ -40,7 +40,7 @@ namespace beast It can also guess how far it's got using a wildly inaccurate algorithm. */ -class BEAST_API DirectoryIterator : LeakChecked , public Uncopyable +class DirectoryIterator : LeakChecked , public Uncopyable { public: //============================================================================== @@ -95,7 +95,7 @@ public: */ bool next (bool* isDirectory, bool* isHidden, - int64* fileSize, + std::int64_t* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly); @@ -122,7 +122,7 @@ private: ~NativeIterator(); bool next (String& filenameFound, - bool* isDirectory, bool* isHidden, int64* fileSize, + bool* isDirectory, bool* isHidden, std::int64_t* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly); class Pimpl; @@ -146,6 +146,6 @@ private: File currentFile; }; -} // namespace beast +} // beast #endif // BEAST_DIRECTORYITERATOR_H_INCLUDED diff --git a/src/beast/modules/beast_core/files/File.cpp b/src/beast/modules/beast_core/files/File.cpp index d06beba707..66b41c9dd2 100644 --- a/src/beast/modules/beast_core/files/File.cpp +++ b/src/beast/modules/beast_core/files/File.cpp @@ -354,7 +354,7 @@ bool File::isAChildOf (const File& potentialParent) const } int File::hashCode() const { return fullPath.hashCode(); } -int64 File::hashCode64() const { return fullPath.hashCode64(); } +std::int64_t File::hashCode64() const { return fullPath.hashCode64(); } //============================================================================== bool File::isAbsolutePath (const String& path) @@ -422,7 +422,7 @@ File File::getSiblingFile (const String& fileName) const } //============================================================================== -String File::descriptionOfSizeInBytes (const int64 bytes) +String File::descriptionOfSizeInBytes (const std::int64_t bytes) { const char* suffix; double divisor = 0; @@ -477,9 +477,9 @@ Result File::createDirectory() const } //============================================================================== -Time File::getLastModificationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (m); } -Time File::getLastAccessTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (a); } -Time File::getCreationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (c); } +Time File::getLastModificationTime() const { std::int64_t m, a, c; getFileTimesInternal (m, a, c); return Time (m); } +Time File::getLastAccessTime() const { std::int64_t m, a, c; getFileTimesInternal (m, a, c); return Time (a); } +Time File::getCreationTime() const { std::int64_t m, a, c; getFileTimesInternal (m, a, c); return Time (c); } bool File::setLastModificationTime (Time t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); } bool File::setLastAccessTime (Time t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); } @@ -694,7 +694,7 @@ FileOutputStream* File::createOutputStream (const size_t bufferSize) const bool File::appendData (const void* const dataToAppend, const size_t numberOfBytes) const { - bassert (((ssize_t) numberOfBytes) >= 0); + bassert (((std::ptrdiff_t) numberOfBytes) >= 0); if (numberOfBytes == 0) return true; diff --git a/src/beast/modules/beast_core/files/File.h b/src/beast/modules/beast_core/files/File.h index 03ad73f654..01832eb9f2 100644 --- a/src/beast/modules/beast_core/files/File.h +++ b/src/beast/modules/beast_core/files/File.h @@ -24,8 +24,17 @@ #ifndef BEAST_FILE_H_INCLUDED #define BEAST_FILE_H_INCLUDED -namespace beast -{ +#include "../containers/Array.h" +#include "../memory/MemoryBlock.h" +#include "../misc/Result.h" +#include "../time/Time.h" +#include "../text/StringArray.h" +#include "../threads/CriticalSection.h" + +namespace beast { + +class FileInputStream; +class FileOutputStream; //============================================================================== /** @@ -39,7 +48,7 @@ namespace beast @see FileInputStream, FileOutputStream */ -class BEAST_API File +class File { public: //============================================================================== @@ -123,14 +132,14 @@ public: @returns the number of bytes in the file, or 0 if it doesn't exist. */ - int64 getSize() const; + std::int64_t getSize() const; /** Utility function to convert a file size in bytes to a neat string description. So for example 100 would return "100 bytes", 2000 would return "2 KB", 2000000 would produce "2 MB", etc. */ - static String descriptionOfSizeInBytes (int64 bytes); + static String descriptionOfSizeInBytes (std::int64_t bytes); //============================================================================== /** Returns the complete, absolute path of this file. @@ -235,7 +244,7 @@ public: This is based on the filename. Obviously it's possible, although unlikely, that two files will have the same hash-code. */ - int64 hashCode64() const; + std::int64_t hashCode64() const; //============================================================================== /** Returns a file that represents a relative (or absolute) sub-path of the current one. @@ -698,14 +707,14 @@ public: @returns the number of bytes free, or 0 if there's a problem finding this out @see getVolumeTotalSize */ - int64 getBytesFreeOnVolume() const; + std::int64_t getBytesFreeOnVolume() const; /** Returns the total size of the drive that contains this file. @returns the total number of bytes that the volume can hold @see getBytesFreeOnVolume */ - int64 getVolumeTotalSize() const; + std::int64_t getVolumeTotalSize() const; /** Returns true if this file is on a CD or DVD drive. */ bool isOnCDRomDrive() const; @@ -842,7 +851,7 @@ public: @see SpecialLocationType */ - static File BEAST_CALLTYPE getSpecialLocation (const SpecialLocationType type); + static File getSpecialLocation (const SpecialLocationType type); //============================================================================== /** Returns a temporary file in the system's temp directory. @@ -946,12 +955,12 @@ private: Result createDirectoryInternal (const String&) const; bool copyInternal (const File&) const; bool moveInternal (const File&) const; - bool setFileTimesInternal (int64 m, int64 a, int64 c) const; - void getFileTimesInternal (int64& m, int64& a, int64& c) const; + bool setFileTimesInternal (std::int64_t m, std::int64_t a, std::int64_t c) const; + void getFileTimesInternal (std::int64_t& m, std::int64_t& a, std::int64_t& c) const; bool setFileReadOnlyInternal (bool) const; }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/files/FileInputStream.cpp b/src/beast/modules/beast_core/files/FileInputStream.cpp index 6edec461b2..d8c17ca4e5 100644 --- a/src/beast/modules/beast_core/files/FileInputStream.cpp +++ b/src/beast/modules/beast_core/files/FileInputStream.cpp @@ -24,7 +24,7 @@ namespace beast { -int64 beast_fileSetPosition (void* handle, int64 pos); +std::int64_t beast_fileSetPosition (void* handle, std::int64_t pos); //============================================================================== FileInputStream::FileInputStream (const File& f) @@ -43,7 +43,7 @@ FileInputStream::~FileInputStream() } //============================================================================== -int64 FileInputStream::getTotalLength() +std::int64_t FileInputStream::getTotalLength() { return file.getSize(); } @@ -72,18 +72,18 @@ bool FileInputStream::isExhausted() return currentPosition >= getTotalLength(); } -int64 FileInputStream::getPosition() +std::int64_t FileInputStream::getPosition() { return currentPosition; } -bool FileInputStream::setPosition (int64 pos) +bool FileInputStream::setPosition (std::int64_t pos) { bassert (openedOk()); if (pos != currentPosition) { - pos = blimit ((int64) 0, getTotalLength(), pos); + pos = blimit ((std::int64_t) 0, getTotalLength(), pos); needToSeek |= (currentPosition != pos); currentPosition = pos; @@ -92,4 +92,4 @@ bool FileInputStream::setPosition (int64 pos) return true; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/files/FileInputStream.h b/src/beast/modules/beast_core/files/FileInputStream.h index cbe26120dc..c946a74026 100644 --- a/src/beast/modules/beast_core/files/FileInputStream.h +++ b/src/beast/modules/beast_core/files/FileInputStream.h @@ -33,7 +33,7 @@ namespace beast @see InputStream, FileOutputStream, File::createInputStream */ -class BEAST_API FileInputStream +class FileInputStream : public InputStream , LeakChecked { @@ -71,17 +71,17 @@ public: //============================================================================== - int64 getTotalLength(); + std::int64_t getTotalLength(); int read (void* destBuffer, int maxBytesToRead); bool isExhausted(); - int64 getPosition(); - bool setPosition (int64 pos); + std::int64_t getPosition(); + bool setPosition (std::int64_t pos); private: //============================================================================== File file; void* fileHandle; - int64 currentPosition; + std::int64_t currentPosition; Result status; bool needToSeek; @@ -90,6 +90,6 @@ private: size_t readInternal (void* buffer, size_t numBytes); }; -} // namespace beast +} // beast #endif // BEAST_FILEINPUTSTREAM_H_INCLUDED diff --git a/src/beast/modules/beast_core/files/FileOutputStream.cpp b/src/beast/modules/beast_core/files/FileOutputStream.cpp index f61829cb7a..0300ebc668 100644 --- a/src/beast/modules/beast_core/files/FileOutputStream.cpp +++ b/src/beast/modules/beast_core/files/FileOutputStream.cpp @@ -24,7 +24,7 @@ namespace beast { -int64 beast_fileSetPosition (void* handle, int64 pos); +std::int64_t beast_fileSetPosition (void* handle, std::int64_t pos); //============================================================================== FileOutputStream::FileOutputStream (const File& f, const size_t bufferSizeToUse) @@ -46,12 +46,12 @@ FileOutputStream::~FileOutputStream() closeHandle(); } -int64 FileOutputStream::getPosition() +std::int64_t FileOutputStream::getPosition() { return currentPosition; } -bool FileOutputStream::setPosition (int64 newPosition) +bool FileOutputStream::setPosition (std::int64_t newPosition) { if (newPosition != currentPosition) { @@ -68,7 +68,7 @@ bool FileOutputStream::flushBuffer() if (bytesInBuffer > 0) { - ok = (writeInternal (buffer, bytesInBuffer) == (ssize_t) bytesInBuffer); + ok = (writeInternal (buffer, bytesInBuffer) == (std::ptrdiff_t) bytesInBuffer); bytesInBuffer = 0; } @@ -83,7 +83,7 @@ void FileOutputStream::flush() bool FileOutputStream::write (const void* const src, const size_t numBytes) { - bassert (src != nullptr && ((ssize_t) numBytes) >= 0); + bassert (src != nullptr && ((std::ptrdiff_t) numBytes) >= 0); if (bytesInBuffer + numBytes < bufferSize) { @@ -104,22 +104,22 @@ bool FileOutputStream::write (const void* const src, const size_t numBytes) } else { - const ssize_t bytesWritten = writeInternal (src, numBytes); + const std::ptrdiff_t bytesWritten = writeInternal (src, numBytes); if (bytesWritten < 0) return false; currentPosition += bytesWritten; - return bytesWritten == (ssize_t) numBytes; + return bytesWritten == (std::ptrdiff_t) numBytes; } } return true; } -bool FileOutputStream::writeRepeatedByte (uint8 byte, size_t numBytes) +bool FileOutputStream::writeRepeatedByte (std::uint8_t byte, size_t numBytes) { - bassert (((ssize_t) numBytes) >= 0); + bassert (((std::ptrdiff_t) numBytes) >= 0); if (bytesInBuffer + numBytes < bufferSize) { @@ -132,4 +132,4 @@ bool FileOutputStream::writeRepeatedByte (uint8 byte, size_t numBytes) return OutputStream::writeRepeatedByte (byte, numBytes); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/files/FileOutputStream.h b/src/beast/modules/beast_core/files/FileOutputStream.h index 18adec0f4f..d8594724eb 100644 --- a/src/beast/modules/beast_core/files/FileOutputStream.h +++ b/src/beast/modules/beast_core/files/FileOutputStream.h @@ -33,7 +33,7 @@ namespace beast @see OutputStream, FileInputStream, File::createOutputStream */ -class BEAST_API FileOutputStream +class FileOutputStream : public OutputStream , LeakChecked { @@ -87,10 +87,10 @@ public: //============================================================================== void flush() override; - int64 getPosition() override; - bool setPosition (int64) override; + std::int64_t getPosition() override; + bool setPosition (std::int64_t) override; bool write (const void*, size_t) override; - bool writeRepeatedByte (uint8 byte, size_t numTimesToRepeat) override; + bool writeRepeatedByte (std::uint8_t byte, size_t numTimesToRepeat) override; private: @@ -98,7 +98,7 @@ private: File file; void* fileHandle; Result status; - int64 currentPosition; + std::int64_t currentPosition; size_t bufferSize, bytesInBuffer; HeapBlock buffer; @@ -106,10 +106,10 @@ private: void closeHandle(); void flushInternal(); bool flushBuffer(); - int64 setPositionInternal (int64); - ssize_t writeInternal (const void*, size_t); + std::int64_t setPositionInternal (std::int64_t); + std::ptrdiff_t writeInternal (const void*, size_t); }; -} // namespace beast +} // beast #endif \ No newline at end of file diff --git a/src/beast/modules/beast_core/files/FileSearchPath.cpp b/src/beast/modules/beast_core/files/FileSearchPath.cpp index 156ccb32ee..ee47fc5bb6 100644 --- a/src/beast/modules/beast_core/files/FileSearchPath.cpp +++ b/src/beast/modules/beast_core/files/FileSearchPath.cpp @@ -168,4 +168,4 @@ bool FileSearchPath::isFileInPath (const File& fileToCheck, return false; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/files/FileSearchPath.h b/src/beast/modules/beast_core/files/FileSearchPath.h index 9bf2a3a231..7e897a2b3e 100644 --- a/src/beast/modules/beast_core/files/FileSearchPath.h +++ b/src/beast/modules/beast_core/files/FileSearchPath.h @@ -33,7 +33,7 @@ namespace beast @see File */ -class BEAST_API FileSearchPath : LeakChecked +class FileSearchPath : LeakChecked { public: //============================================================================== @@ -158,6 +158,6 @@ private: void init (const String& path); }; -} // namespace beast +} // beast #endif // BEAST_FILESEARCHPATH_H_INCLUDED diff --git a/src/beast/modules/beast_core/files/RandomAccessFile.cpp b/src/beast/modules/beast_core/files/RandomAccessFile.cpp index 2376079cf0..73a2e3527f 100644 --- a/src/beast/modules/beast_core/files/RandomAccessFile.cpp +++ b/src/beast/modules/beast_core/files/RandomAccessFile.cpp @@ -68,7 +68,7 @@ Result RandomAccessFile::read (void* buffer, ByteCount numBytes, ByteCount* pAct Result RandomAccessFile::write (const void* data, ByteCount numBytes, ByteCount* pActualAmount) { - bassert (data != nullptr && ((ssize_t) numBytes) >= 0); + bassert (data != nullptr && ((std::ptrdiff_t) numBytes) >= 0); Result result (Result::ok ()); @@ -128,7 +128,7 @@ public: static void createRecords (HeapBlock & records, int numRecords, int maxBytes, - int64 seedValue) + std::int64_t seedValue) { using namespace UnitTestUtilities; @@ -157,7 +157,7 @@ public: void writeRecords (RandomAccessFile& file, int numRecords, HeapBlock const& records, - int64 seedValue) + std::int64_t seedValue) { using namespace UnitTestUtilities; @@ -181,7 +181,7 @@ public: void readRecords (RandomAccessFile& file, int numRecords, HeapBlock const& records, - int64 seedValue) + std::int64_t seedValue) { using namespace UnitTestUtilities; diff --git a/src/beast/modules/beast_core/files/RandomAccessFile.h b/src/beast/modules/beast_core/files/RandomAccessFile.h index d6c409a2f3..509f2146c8 100644 --- a/src/beast/modules/beast_core/files/RandomAccessFile.h +++ b/src/beast/modules/beast_core/files/RandomAccessFile.h @@ -39,14 +39,14 @@ namespace beast @see FileInputStream, FileOutputStream */ -class BEAST_API RandomAccessFile : public Uncopyable, LeakChecked +class RandomAccessFile : public Uncopyable, LeakChecked { public: /** The type of an FileOffset. This can be useful when writing templates. */ - typedef int64 FileOffset; + typedef std::int64_t FileOffset; /** The type of a byte count. @@ -194,7 +194,7 @@ private: FileOffset currentPosition; }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/files/TemporaryFile.cpp b/src/beast/modules/beast_core/files/TemporaryFile.cpp index 9a91b3d4b5..d552c34998 100644 --- a/src/beast/modules/beast_core/files/TemporaryFile.cpp +++ b/src/beast/modules/beast_core/files/TemporaryFile.cpp @@ -114,4 +114,4 @@ bool TemporaryFile::deleteTemporaryFile() const return false; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/files/TemporaryFile.h b/src/beast/modules/beast_core/files/TemporaryFile.h index b2f13fd4d5..e11c04ac09 100644 --- a/src/beast/modules/beast_core/files/TemporaryFile.h +++ b/src/beast/modules/beast_core/files/TemporaryFile.h @@ -65,7 +65,7 @@ namespace beast @see File, FileOutputStream */ -class BEAST_API TemporaryFile : LeakChecked , public Uncopyable +class TemporaryFile : LeakChecked , public Uncopyable { public: //============================================================================== @@ -161,6 +161,6 @@ private: const File temporaryFile, targetFile; }; -} // namespace beast +} // beast #endif // BEAST_TEMPORARYFILE_H_INCLUDED diff --git a/src/beast/modules/beast_core/logging/Logger.cpp b/src/beast/modules/beast_core/logging/Logger.cpp index ba781879cb..317f82698a 100644 --- a/src/beast/modules/beast_core/logging/Logger.cpp +++ b/src/beast/modules/beast_core/logging/Logger.cpp @@ -60,4 +60,4 @@ void logAssertion (const char* const filename, const int lineNum) } #endif -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/logging/Logger.h b/src/beast/modules/beast_core/logging/Logger.h index 8ada8ae7a6..d41d458629 100644 --- a/src/beast/modules/beast_core/logging/Logger.h +++ b/src/beast/modules/beast_core/logging/Logger.h @@ -37,7 +37,7 @@ namespace beast The logger class also contains methods for writing messages to the debugger's output stream. */ -class BEAST_API Logger +class Logger { public: //============================================================================== @@ -51,7 +51,7 @@ public: the caller must make sure that it is not deleted while still being used. A null pointer can be passed-in to disable any logging. */ - static void BEAST_CALLTYPE setCurrentLogger (Logger* newLogger) noexcept; + static void setCurrentLogger (Logger* newLogger) noexcept; /** Returns the current logger, or nullptr if none has been set. */ static Logger* getCurrentLogger() noexcept; @@ -63,7 +63,7 @@ public: @see logMessage */ - static void BEAST_CALLTYPE writeToLog (const String& message); + static void writeToLog (const String& message); //============================================================================== @@ -72,7 +72,7 @@ public: This can be called directly, or by using the DBG() macro in CompilerConfig.h (which will avoid calling the method in non-debug builds). */ - static void BEAST_CALLTYPE outputDebugString (const String& text); + static void outputDebugString (const String& text); protected: @@ -88,6 +88,6 @@ private: static Logger* currentLogger; }; -} // namespace beast +} // beast #endif // BEAST_LOGGER_H_INCLUDED diff --git a/src/beast/modules/beast_core/maths/Math.h b/src/beast/modules/beast_core/maths/Math.h index 26f5bcfe4f..0365c44331 100644 --- a/src/beast/modules/beast_core/maths/Math.h +++ b/src/beast/modules/beast_core/maths/Math.h @@ -84,6 +84,6 @@ inline T radiansToDegrees (U radians) return deg; } -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/maths/Random.cpp b/src/beast/modules/beast_core/maths/Random.cpp index 67c9b9fb24..496c8fc957 100644 --- a/src/beast/modules/beast_core/maths/Random.cpp +++ b/src/beast/modules/beast_core/maths/Random.cpp @@ -25,7 +25,7 @@ namespace beast { -Random::Random (const int64 seedValue) noexcept +Random::Random (const std::int64_t seedValue) noexcept : seed (seedValue) { nextInt (); // fixes a bug where the first int is always 0 @@ -41,23 +41,23 @@ Random::~Random() noexcept { } -void Random::setSeed (const int64 newSeed) noexcept +void Random::setSeed (const std::int64_t newSeed) noexcept { seed = newSeed; nextInt (); // fixes a bug where the first int is always 0 } -void Random::combineSeed (const int64 seedValue) noexcept +void Random::combineSeed (const std::int64_t seedValue) noexcept { seed ^= nextInt64() ^ seedValue; } void Random::setSeedRandomly() { - static int64 globalSeed = 0; + static std::int64_t globalSeed = 0; - combineSeed (globalSeed ^ (int64) (pointer_sized_int) this); + combineSeed (globalSeed ^ (std::int64_t) (std::intptr_t) this); combineSeed (Time::getMillisecondCounter()); combineSeed (Time::getHighResolutionTicks()); combineSeed (Time::getHighResolutionTicksPerSecond()); @@ -76,7 +76,7 @@ Random& Random::getSystemRandom() noexcept //============================================================================== int Random::nextInt() noexcept { - seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff); + seed = (seed * 0x5deece66dLL + 11) & 0xffffffffffffULL; return (int) (seed >> 16); } @@ -84,12 +84,12 @@ int Random::nextInt() noexcept int Random::nextInt (const int maxValue) noexcept { bassert (maxValue > 0); - return (int) ((((unsigned int) nextInt()) * (uint64) maxValue) >> 32); + return (int) ((((unsigned int) nextInt()) * (std::uint64_t) maxValue) >> 32); } -int64 Random::nextInt64() noexcept +std::int64_t Random::nextInt64() noexcept { - return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt(); + return (((std::int64_t) nextInt()) << 32) | (std::int64_t) (std::uint64_t) (std::uint32_t) nextInt(); } bool Random::nextBool() noexcept @@ -99,12 +99,12 @@ bool Random::nextBool() noexcept float Random::nextFloat() noexcept { - return static_cast (nextInt()) / (float) 0xffffffff; + return static_cast (nextInt()) / (float) 0xffffffff; } double Random::nextDouble() noexcept { - return static_cast (nextInt()) / (double) 0xffffffff; + return static_cast (nextInt()) / (double) 0xffffffff; } void Random::fillBitsRandomly (void* const buffer, size_t bytes) diff --git a/src/beast/modules/beast_core/maths/Random.h b/src/beast/modules/beast_core/maths/Random.h index d67ebbae9f..6f03194134 100644 --- a/src/beast/modules/beast_core/maths/Random.h +++ b/src/beast/modules/beast_core/maths/Random.h @@ -45,7 +45,7 @@ public: new Random (Time::currentTimeMillis()) */ - explicit Random (int64 seedValue) noexcept; + explicit Random (std::int64_t seedValue) noexcept; /** Creates a Random object using a random seed value. Internally, this calls setSeedRandomly() to randomise the seed. @@ -71,7 +71,7 @@ public: @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff */ - int64 nextInt64() noexcept; + std::int64_t nextInt64() noexcept; /** Returns the next random floating-point number. @@ -94,13 +94,13 @@ public: //============================================================================== /** Resets this Random object to a given seed value. */ - void setSeed (int64 newSeed) noexcept; + void setSeed (std::int64_t newSeed) noexcept; /** Merges this object's seed with another value. This sets the seed to be a value created by combining the current seed and this new value. */ - void combineSeed (int64 seedValue) noexcept; + void combineSeed (std::int64_t seedValue) noexcept; /** Reseeds this generator using a value generated from various semi-random system properties like the current time, etc. @@ -120,9 +120,9 @@ public: private: //============================================================================== - int64 seed; + std::int64_t seed; }; -} // namespace beast +} // beast #endif // BEAST_RANDOM_H_INCLUDED diff --git a/src/beast/modules/beast_core/maths/Range.h b/src/beast/modules/beast_core/maths/Range.h index e184ebefb9..f1a65f9f04 100644 --- a/src/beast/modules/beast_core/maths/Range.h +++ b/src/beast/modules/beast_core/maths/Range.h @@ -258,6 +258,6 @@ private: ValueType start, end; }; -} // namespace beast +} // beast #endif // BEAST_RANGE_H_INCLUDED diff --git a/src/beast/modules/beast_core/memory/MemoryBlock.cpp b/src/beast/modules/beast_core/memory/MemoryBlock.cpp index 9c2e3c13b9..0eccc652a6 100644 --- a/src/beast/modules/beast_core/memory/MemoryBlock.cpp +++ b/src/beast/modules/beast_core/memory/MemoryBlock.cpp @@ -56,7 +56,7 @@ MemoryBlock::MemoryBlock (const MemoryBlock& other) MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes) : size (sizeInBytes) { - bassert (((ssize_t) sizeInBytes) >= 0); + bassert (((std::ptrdiff_t) sizeInBytes) >= 0); if (size > 0) { @@ -160,7 +160,7 @@ void MemoryBlock::swapWith (MemoryBlock& other) noexcept } //============================================================================== -void MemoryBlock::fillWith (const uint8 value) noexcept +void MemoryBlock::fillWith (const std::uint8_t value) noexcept { memset (data, (int) value, size); } @@ -295,16 +295,16 @@ void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int b { size_t byte = bitRangeStart >> 3; size_t offsetInByte = bitRangeStart & 7; - uint32 mask = ~((((uint32) 0xffffffff) << (32 - numBits)) >> (32 - numBits)); + std::uint32_t mask = ~((((std::uint32_t) 0xffffffff) << (32 - numBits)) >> (32 - numBits)); while (numBits > 0 && (size_t) byte < size) { const size_t bitsThisTime = bmin (numBits, 8 - offsetInByte); - const uint32 tempMask = (mask << offsetInByte) | ~((((uint32) 0xffffffff) >> offsetInByte) << offsetInByte); - const uint32 tempBits = (uint32) bitsToSet << offsetInByte; + const std::uint32_t tempMask = (mask << offsetInByte) | ~((((std::uint32_t) 0xffffffff) >> offsetInByte) << offsetInByte); + const std::uint32_t tempBits = (std::uint32_t) bitsToSet << offsetInByte; - data[byte] = (char) (((uint32) data[byte] & tempMask) | tempBits); + data[byte] = (char) (((std::uint32_t) data[byte] & tempMask) | tempBits); ++byte; numBits -= bitsThisTime; @@ -366,7 +366,7 @@ String MemoryBlock::toBase64Encoding() const d.write ('.'); for (size_t i = 0; i < numChars; ++i) - d.write ((beast_wchar) (uint8) base64EncodingTable [getBitRange (i * 6, 6)]); + d.write ((beast_wchar) (std::uint8_t) base64EncodingTable [getBitRange (i * 6, 6)]); d.writeNull(); return destString; @@ -407,4 +407,4 @@ bool MemoryBlock::fromBase64Encoding (const String& s) return true; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/memory/MemoryBlock.h b/src/beast/modules/beast_core/memory/MemoryBlock.h index c411192d0e..7e365dfd58 100644 --- a/src/beast/modules/beast_core/memory/MemoryBlock.h +++ b/src/beast/modules/beast_core/memory/MemoryBlock.h @@ -24,15 +24,16 @@ #ifndef BEAST_MEMORYBLOCK_H_INCLUDED #define BEAST_MEMORYBLOCK_H_INCLUDED -namespace beast -{ +#include "../../../beast/utility/LeakChecked.h" + +namespace beast { //============================================================================== /** A class to hold a resizable block of raw data. */ -class BEAST_API MemoryBlock : LeakChecked +class MemoryBlock : LeakChecked { public: //============================================================================== @@ -160,7 +161,7 @@ public: This is handy for clearing a block of memory to zero. */ - void fillWith (uint8 valueToUse) noexcept; + void fillWith (std::uint8_t valueToUse) noexcept; /** Adds another block of data to the end of this one. The data pointer must not be null. This block's size will be increased accordingly. @@ -267,7 +268,7 @@ private: size_t size; }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/memory/SharedSingleton.h b/src/beast/modules/beast_core/memory/SharedSingleton.h index 28b8ee8d37..fca8841ed8 100644 --- a/src/beast/modules/beast_core/memory/SharedSingleton.h +++ b/src/beast/modules/beast_core/memory/SharedSingleton.h @@ -20,6 +20,10 @@ #ifndef BEAST_SHAREDSINGLETON_H_INCLUDED #define BEAST_SHAREDSINGLETON_H_INCLUDED +#include "../../../beast/threads/SpinLock.h" +#include "../../../beast/smart_ptr/SharedPtr.h" +#include "../time/AtExitHook.h" + namespace beast { @@ -38,7 +42,7 @@ namespace beast @ingroup beast_core */ /** @{ */ -class BEAST_API SingletonLifetime +class SingletonLifetime { public: // It would be nice if we didn't have to qualify the enumeration but @@ -88,7 +92,7 @@ public: SharedSingleton* instance = staticData.instance; if (instance == nullptr) { - LockType::ScopedLockType lock (staticData.mutex); + std::lock_guard lock (staticData.mutex); instance = staticData.instance; if (instance == nullptr) { @@ -138,7 +142,7 @@ private: // { StaticData& staticData (getStaticData ()); - LockType::ScopedLockType lock (staticData.mutex); + std::lock_guard lock (staticData.mutex); if (this->getReferenceCount() != 0) { @@ -180,7 +184,7 @@ private: static StaticData& getStaticData () { - static uint8 storage [sizeof (StaticData)]; + static std::uint8_t storage [sizeof (StaticData)]; return *(reinterpret_cast (&storage [0])); } @@ -193,6 +197,6 @@ private: //------------------------------------------------------------------------------ -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/misc/Result.cpp b/src/beast/modules/beast_core/misc/Result.cpp index 36dfe59bd1..31a9ecad36 100644 --- a/src/beast/modules/beast_core/misc/Result.cpp +++ b/src/beast/modules/beast_core/misc/Result.cpp @@ -80,4 +80,4 @@ Result::operator bool() const noexcept { return errorMessage.isEmpty(); } bool Result::failed() const noexcept { return errorMessage.isNotEmpty(); } bool Result::operator!() const noexcept { return errorMessage.isNotEmpty(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/misc/Result.h b/src/beast/modules/beast_core/misc/Result.h index 661137b2a3..c503bb0408 100644 --- a/src/beast/modules/beast_core/misc/Result.h +++ b/src/beast/modules/beast_core/misc/Result.h @@ -53,7 +53,7 @@ namespace beast } @endcode */ -class BEAST_API Result +class Result { public: //============================================================================== @@ -116,7 +116,7 @@ private: operator void*() const; }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/misc/WindowsRegistry.h b/src/beast/modules/beast_core/misc/WindowsRegistry.h index 504369791b..2612d7755a 100644 --- a/src/beast/modules/beast_core/misc/WindowsRegistry.h +++ b/src/beast/modules/beast_core/misc/WindowsRegistry.h @@ -56,7 +56,7 @@ public: e.g. "HKEY_CURRENT_USER\Software\foo\bar" @returns a DWORD indicating the type of the key. */ - static uint32 getBinaryValue (const String& regValuePath, MemoryBlock& resultData); + static std::uint32_t getBinaryValue (const String& regValuePath, MemoryBlock& resultData); /** Sets a registry value as a string. This will take care of creating any groups needed to get to the given registry value. @@ -66,12 +66,12 @@ public: /** Sets a registry value as a DWORD. This will take care of creating any groups needed to get to the given registry value. */ - static bool setValue (const String& regValuePath, uint32 value); + static bool setValue (const String& regValuePath, std::uint32_t value); /** Sets a registry value as a QWORD. This will take care of creating any groups needed to get to the given registry value. */ - static bool setValue (const String& regValuePath, uint64 value); + static bool setValue (const String& regValuePath, std::uint64_t value); /** Sets a registry value as a binary block. This will take care of creating any groups needed to get to the given registry value. @@ -119,6 +119,6 @@ private: #endif -} // namespace beast +} // beast #endif // BEAST_WINDOWSREGISTRY_H_INCLUDED diff --git a/src/beast/modules/beast_core/native/bsd_Files.cpp b/src/beast/modules/beast_core/native/bsd_Files.cpp index 69ba29c81b..9e5d7884b8 100644 --- a/src/beast/modules/beast_core/native/bsd_Files.cpp +++ b/src/beast/modules/beast_core/native/bsd_Files.cpp @@ -261,7 +261,7 @@ public: } bool next (String& filenameFound, - bool* const isDir, bool* const isHidden, int64* const fileSize, + bool* const isDir, bool* const isHidden, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { if (dir != nullptr) @@ -310,7 +310,7 @@ DirectoryIterator::NativeIterator::~NativeIterator() } bool DirectoryIterator::NativeIterator::next (String& filenameFound, - bool* const isDir, bool* const isHidden, int64* const fileSize, + bool* const isDir, bool* const isHidden, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly); @@ -371,4 +371,4 @@ void File::revealToUser() const getParentDirectory().startAsProcess(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/bsd_Network.cpp b/src/beast/modules/beast_core/native/bsd_Network.cpp deleted file mode 100644 index 951ca6aa45..0000000000 --- a/src/beast/modules/beast_core/native/bsd_Network.cpp +++ /dev/null @@ -1,37 +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 -{ - -bool Process::openEmailWithAttachments (const String& /* targetEmailAddress */, - const String& /* emailSubject */, - const String& /* bodyText */, - const StringArray& /* filesToAttach */) -{ - bassertfalse; // xxx todo - - return false; -} - -} // namespace beast diff --git a/src/beast/modules/beast_core/native/bsd_SystemStats.cpp b/src/beast/modules/beast_core/native/bsd_SystemStats.cpp index f4e288e591..407198bac3 100644 --- a/src/beast/modules/beast_core/native/bsd_SystemStats.cpp +++ b/src/beast/modules/beast_core/native/bsd_SystemStats.cpp @@ -318,7 +318,7 @@ void CPUInformation::initialise() noexcept } //============================================================================== -uint32 beast_millisecondsSinceStartup() noexcept +std::uint32_t beast_millisecondsSinceStartup() noexcept { timespec t; clock_gettime (CLOCK_MONOTONIC, &t); @@ -326,15 +326,15 @@ uint32 beast_millisecondsSinceStartup() noexcept return t.tv_sec * 1000 + t.tv_nsec / 1000000; } -int64 Time::getHighResolutionTicks() noexcept +std::int64_t Time::getHighResolutionTicks() noexcept { timespec t; clock_gettime (CLOCK_MONOTONIC, &t); - return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / 1000); + return (t.tv_sec * (std::int64_t) 1000000) + (t.tv_nsec / 1000); } -int64 Time::getHighResolutionTicksPerSecond() noexcept +std::int64_t Time::getHighResolutionTicksPerSecond() noexcept { return 1000000; // (microseconds) } @@ -353,4 +353,4 @@ bool Time::setSystemTimeToThisTime() const return settimeofday (&t, 0) == 0; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/bsd_Threads.cpp b/src/beast/modules/beast_core/native/bsd_Threads.cpp index 680b9fbf2a..9f7226686e 100644 --- a/src/beast/modules/beast_core/native/bsd_Threads.cpp +++ b/src/beast/modules/beast_core/native/bsd_Threads.cpp @@ -57,7 +57,7 @@ bool beast_isRunningUnderDebugger() return false; } -BEAST_API bool BEAST_CALLTYPE Process::isRunningUnderDebugger() +bool Process::isRunningUnderDebugger() { return beast_isRunningUnderDebugger(); } @@ -71,4 +71,4 @@ static void swapUserAndEffectiveUser() void Process::raisePrivilege() { if (geteuid() != 0 && getuid() == 0) swapUserAndEffectiveUser(); } void Process::lowerPrivilege() { if (geteuid() == 0 && getuid() != 0) swapUserAndEffectiveUser(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/linux_Files.cpp b/src/beast/modules/beast_core/native/linux_Files.cpp index 1f05ee0f9d..11551684c9 100644 --- a/src/beast/modules/beast_core/native/linux_Files.cpp +++ b/src/beast/modules/beast_core/native/linux_Files.cpp @@ -261,7 +261,7 @@ public: } bool next (String& filenameFound, - bool* const isDir, bool* const isHidden, int64* const fileSize, + bool* const isDir, bool* const isHidden, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { if (dir != nullptr) @@ -310,7 +310,7 @@ DirectoryIterator::NativeIterator::~NativeIterator() } bool DirectoryIterator::NativeIterator::next (String& filenameFound, - bool* const isDir, bool* const isHidden, int64* const fileSize, + bool* const isDir, bool* const isHidden, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly); @@ -371,4 +371,4 @@ void File::revealToUser() const getParentDirectory().startAsProcess(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/linux_Network.cpp b/src/beast/modules/beast_core/native/linux_Network.cpp deleted file mode 100644 index 951ca6aa45..0000000000 --- a/src/beast/modules/beast_core/native/linux_Network.cpp +++ /dev/null @@ -1,37 +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 -{ - -bool Process::openEmailWithAttachments (const String& /* targetEmailAddress */, - const String& /* emailSubject */, - const String& /* bodyText */, - const StringArray& /* filesToAttach */) -{ - bassertfalse; // xxx todo - - return false; -} - -} // namespace beast diff --git a/src/beast/modules/beast_core/native/linux_SystemStats.cpp b/src/beast/modules/beast_core/native/linux_SystemStats.cpp index f74c06671a..88372945da 100644 --- a/src/beast/modules/beast_core/native/linux_SystemStats.cpp +++ b/src/beast/modules/beast_core/native/linux_SystemStats.cpp @@ -143,7 +143,7 @@ void CPUInformation::initialise() noexcept } //============================================================================== -uint32 beast_millisecondsSinceStartup() noexcept +std::uint32_t beast_millisecondsSinceStartup() noexcept { timespec t; clock_gettime (CLOCK_MONOTONIC, &t); @@ -151,15 +151,15 @@ uint32 beast_millisecondsSinceStartup() noexcept return t.tv_sec * 1000 + t.tv_nsec / 1000000; } -int64 Time::getHighResolutionTicks() noexcept +std::int64_t Time::getHighResolutionTicks() noexcept { timespec t; clock_gettime (CLOCK_MONOTONIC, &t); - return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / 1000); + return (t.tv_sec * (std::int64_t) 1000000) + (t.tv_nsec / 1000); } -int64 Time::getHighResolutionTicksPerSecond() noexcept +std::int64_t Time::getHighResolutionTicksPerSecond() noexcept { return 1000000; // (microseconds) } @@ -178,4 +178,4 @@ bool Time::setSystemTimeToThisTime() const return settimeofday (&t, 0) == 0; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/linux_Threads.cpp b/src/beast/modules/beast_core/native/linux_Threads.cpp index 64af66fc4b..74c1e3fe38 100644 --- a/src/beast/modules/beast_core/native/linux_Threads.cpp +++ b/src/beast/modules/beast_core/native/linux_Threads.cpp @@ -68,7 +68,7 @@ bool beast_isRunningUnderDebugger() return testResult < 0; } -BEAST_API bool BEAST_CALLTYPE Process::isRunningUnderDebugger() +bool Process::isRunningUnderDebugger() { return beast_isRunningUnderDebugger(); } @@ -82,4 +82,4 @@ static void swapUserAndEffectiveUser() void Process::raisePrivilege() { if (geteuid() != 0 && getuid() == 0) swapUserAndEffectiveUser(); } void Process::lowerPrivilege() { if (geteuid() == 0 && getuid() != 0) swapUserAndEffectiveUser(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/mac_Files.mm b/src/beast/modules/beast_core/native/mac_Files.mm index dc2ad72b7d..71eb1c52cb 100644 --- a/src/beast/modules/beast_core/native/mac_Files.mm +++ b/src/beast/modules/beast_core/native/mac_Files.mm @@ -332,7 +332,7 @@ public: } bool next (String& filenameFound, - bool* const isDir, bool* const isHidden, int64* const fileSize, + bool* const isDir, bool* const isHidden, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { BEAST_AUTORELEASEPOOL @@ -380,7 +380,7 @@ DirectoryIterator::NativeIterator::~NativeIterator() } bool DirectoryIterator::NativeIterator::next (String& filenameFound, - bool* const isDir, bool* const isHidden, int64* const fileSize, + bool* const isDir, bool* const isHidden, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly); @@ -481,4 +481,4 @@ void File::addToDock() const } #endif -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/mac_Network.mm b/src/beast/modules/beast_core/native/mac_Network.mm deleted file mode 100644 index f042da0faa..0000000000 --- a/src/beast/modules/beast_core/native/mac_Network.mm +++ /dev/null @@ -1,75 +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 -{ - -bool Process::openEmailWithAttachments (const String& targetEmailAddress, - const String& emailSubject, - const String& bodyText, - const StringArray& filesToAttach) -{ - #if BEAST_IOS - //xxx probably need to use MFMailComposeViewController - bassertfalse; - return false; - #else - BEAST_AUTORELEASEPOOL - { - String script; - script << "tell application \"Mail\"\r\n" - "set newMessage to make new outgoing message with properties {subject:\"" - << emailSubject.replace ("\"", "\\\"") - << "\", content:\"" - << bodyText.replace ("\"", "\\\"") - << "\" & return & return}\r\n" - "tell newMessage\r\n" - "set visible to true\r\n" - "set sender to \"sdfsdfsdfewf\"\r\n" - "make new to recipient at end of to recipients with properties {address:\"" - << targetEmailAddress - << "\"}\r\n"; - - for (int i = 0; i < filesToAttach.size(); ++i) - { - script << "tell content\r\n" - "make new attachment with properties {file name:\"" - << filesToAttach[i].replace ("\"", "\\\"") - << "\"} at after the last paragraph\r\n" - "end tell\r\n"; - } - - script << "end tell\r\n" - "end tell\r\n"; - - NSAppleScript* s = [[NSAppleScript alloc] initWithSource: beastStringToNS (script)]; - NSDictionary* error = nil; - const bool ok = [s executeAndReturnError: &error] != nil; - [s release]; - - return ok; - } - #endif -} - -} // namespace beast diff --git a/src/beast/modules/beast_core/native/mac_Strings.mm b/src/beast/modules/beast_core/native/mac_Strings.mm index befece2cfc..5c80696a9d 100644 --- a/src/beast/modules/beast_core/native/mac_Strings.mm +++ b/src/beast/modules/beast_core/native/mac_Strings.mm @@ -93,4 +93,4 @@ String String::convertToPrecomposedUnicode() const #endif } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/mac_SystemStats.mm b/src/beast/modules/beast_core/native/mac_SystemStats.mm index 040f5a7330..fb900160c5 100644 --- a/src/beast/modules/beast_core/native/mac_SystemStats.mm +++ b/src/beast/modules/beast_core/native/mac_SystemStats.mm @@ -48,9 +48,9 @@ void Logger::outputDebugString (const String& text) namespace SystemStatsHelpers { #if BEAST_INTEL && ! BEAST_NO_INLINE_ASM - static void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type) + static void doCPUID (std::uint32_t& a, std::uint32_t& b, std::uint32_t& c, std::uint32_t& d, std::uint32_t type) { - uint32 la = a, lb = b, lc = c, ld = d; + std::uint32_t la = a, lb = b, lc = c, ld = d; asm ("mov %%ebx, %%esi \n\t" "cpuid \n\t" @@ -70,7 +70,7 @@ namespace SystemStatsHelpers void CPUInformation::initialise() noexcept { #if BEAST_INTEL && ! BEAST_NO_INLINE_ASM - uint32 a = 0, b = 0, d = 0, c = 0; + std::uint32_t a = 0, b = 0, d = 0, c = 0; SystemStatsHelpers::doCPUID (a, b, c, d, 1); hasMMX = (d & (1u << 23)) != 0; @@ -154,7 +154,7 @@ bool SystemStats::isOperatingSystem64Bit() int SystemStats::getMemorySizeInMegabytes() { - uint64 mem = 0; + std::uint64_t mem = 0; size_t memSize = sizeof (mem); int mib[] = { CTL_HW, HW_MEMSIZE }; sysctl (mib, 2, &mem, &memSize, 0, 0); @@ -164,8 +164,8 @@ int SystemStats::getMemorySizeInMegabytes() String SystemStats::getCpuVendor() { #if BEAST_INTEL && ! BEAST_NO_INLINE_ASM - uint32 dummy = 0; - uint32 vendor[4] = { 0 }; + std::uint32_t dummy = 0; + std::uint32_t vendor[4] = { 0 }; SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0); @@ -177,7 +177,7 @@ String SystemStats::getCpuVendor() int SystemStats::getCpuSpeedInMegaherz() { - uint64 speedHz = 0; + std::uint64_t speedHz = 0; size_t speedSize = sizeof (speedHz); int mib[] = { CTL_HW, HW_CPU_FREQ }; sysctl (mib, 2, &speedHz, &speedSize, 0, 0); @@ -246,16 +246,16 @@ public: else { numerator = timebase.numer; - denominator = timebase.denom * (uint64) 1000000; + denominator = timebase.denom * (std::uint64_t) 1000000; } - highResTimerFrequency = (timebase.denom * (uint64) 1000000000) / timebase.numer; + highResTimerFrequency = (timebase.denom * (std::uint64_t) 1000000000) / timebase.numer; highResTimerToMillisecRatio = numerator / (double) denominator; } - inline uint32 millisecondsSinceStartup() const noexcept + inline std::uint32_t millisecondsSinceStartup() const noexcept { - return (uint32) ((mach_absolute_time() * numerator) / denominator); + return (std::uint32_t) ((mach_absolute_time() * numerator) / denominator); } inline double getMillisecondCounterHiRes() const noexcept @@ -263,10 +263,10 @@ public: return mach_absolute_time() * highResTimerToMillisecRatio; } - int64 highResTimerFrequency; + std::int64_t highResTimerFrequency; private: - uint64 numerator, denominator; + std::uint64_t numerator, denominator; double highResTimerToMillisecRatio; }; @@ -276,10 +276,10 @@ static HiResCounterHandler& hiResCounterHandler() return hiResCounterHandler; } -uint32 beast_millisecondsSinceStartup() noexcept { return hiResCounterHandler().millisecondsSinceStartup(); } +std::uint32_t beast_millisecondsSinceStartup() noexcept { return hiResCounterHandler().millisecondsSinceStartup(); } double Time::getMillisecondCounterHiRes() noexcept { return hiResCounterHandler().getMillisecondCounterHiRes(); } -int64 Time::getHighResolutionTicksPerSecond() noexcept { return hiResCounterHandler().highResTimerFrequency; } -int64 Time::getHighResolutionTicks() noexcept { return (int64) mach_absolute_time(); } +std::int64_t Time::getHighResolutionTicksPerSecond() noexcept { return hiResCounterHandler().highResTimerFrequency; } +std::int64_t Time::getHighResolutionTicks() noexcept { return (std::int64_t) mach_absolute_time(); } bool Time::setSystemTimeToThisTime() const { @@ -293,4 +293,4 @@ int SystemStats::getPageSize() return (int) NSPageSize(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/mac_Threads.mm b/src/beast/modules/beast_core/native/mac_Threads.mm index fd64ed6c9b..ff38250353 100644 --- a/src/beast/modules/beast_core/native/mac_Threads.mm +++ b/src/beast/modules/beast_core/native/mac_Threads.mm @@ -78,9 +78,9 @@ bool beast_isRunningUnderDebugger() return testResult > 0; } -BEAST_API bool BEAST_CALLTYPE Process::isRunningUnderDebugger() +bool Process::isRunningUnderDebugger() { return beast_isRunningUnderDebugger(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/osx_ObjCHelpers.h b/src/beast/modules/beast_core/native/osx_ObjCHelpers.h index d4f19bc719..14f8186cad 100644 --- a/src/beast/modules/beast_core/native/osx_ObjCHelpers.h +++ b/src/beast/modules/beast_core/native/osx_ObjCHelpers.h @@ -149,6 +149,6 @@ private: } }; -} // namespace beast +} // beast #endif // BEAST_OSX_OBJCHELPERS_H_INCLUDED diff --git a/src/beast/modules/beast_core/native/posix_SharedCode.h b/src/beast/modules/beast_core/native/posix_SharedCode.h index f49b2e254e..c57f0fd869 100644 --- a/src/beast/modules/beast_core/native/posix_SharedCode.h +++ b/src/beast/modules/beast_core/native/posix_SharedCode.h @@ -128,7 +128,7 @@ namespace return statfs (f.getFullPathName().toUTF8(), &result) == 0; } - void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize, + void updateStatInfoForFile (const String& path, bool* const isDir, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { if (isDir != nullptr || fileSize != nullptr || modTime != nullptr || creationTime != nullptr) @@ -138,8 +138,8 @@ namespace if (isDir != nullptr) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0); if (fileSize != nullptr) *fileSize = statOk ? info.st_size : 0; - if (modTime != nullptr) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0); - if (creationTime != nullptr) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0); + if (modTime != nullptr) *modTime = Time (statOk ? (std::int64_t) info.st_mtime * 1000 : 0); + if (creationTime != nullptr) *creationTime = Time (statOk ? (std::int64_t) info.st_ctime * 1000 : 0); } if (isReadOnly != nullptr) @@ -156,8 +156,8 @@ namespace return value == -1 ? getResultForErrno() : Result::ok(); } - int getFD (void* handle) noexcept { return (int) (pointer_sized_int) handle; } - void* fdToVoidPointer (int fd) noexcept { return (void*) (pointer_sized_int) fd; } + int getFD (void* handle) noexcept { return (int) (std::intptr_t) handle; } + void* fdToVoidPointer (int fd) noexcept { return (void*) (std::intptr_t) fd; } } bool File::isDirectory() const @@ -179,7 +179,7 @@ bool File::existsAsFile() const return exists() && ! isDirectory(); } -int64 File::getSize() const +std::int64_t File::getSize() const { beast_statStruct info; return beast_stat (fullPath, info) ? info.st_size : 0; @@ -214,7 +214,7 @@ bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const return chmod (fullPath.toUTF8(), info.st_mode) == 0; } -void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const +void File::getFileTimesInternal (std::int64_t& modificationTime, std::int64_t& accessTime, std::int64_t& creationTime) const { modificationTime = 0; accessTime = 0; @@ -223,13 +223,13 @@ void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int beast_statStruct info; if (beast_stat (fullPath, info)) { - modificationTime = (int64) info.st_mtime * 1000; - accessTime = (int64) info.st_atime * 1000; - creationTime = (int64) info.st_ctime * 1000; + modificationTime = (std::int64_t) info.st_mtime * 1000; + accessTime = (std::int64_t) info.st_atime * 1000; + creationTime = (std::int64_t) info.st_ctime * 1000; } } -bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const +bool File::setFileTimesInternal (std::int64_t modificationTime, std::int64_t accessTime, std::int64_t /*creationTime*/) const { beast_statStruct info; @@ -278,7 +278,7 @@ Result File::createDirectoryInternal (const String& fileName) const } //===================================================================== -int64 beast_fileSetPosition (void* handle, int64 pos) +std::int64_t beast_fileSetPosition (void* handle, std::int64_t pos) { if (handle != 0 && lseek (getFD (handle), pos, SEEK_SET) == pos) return pos; @@ -307,7 +307,7 @@ void FileInputStream::closeHandle() size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes) { - ssize_t result = 0; + std::ptrdiff_t result = 0; if (fileHandle != 0) { @@ -369,9 +369,9 @@ void FileOutputStream::closeHandle() } } -ssize_t FileOutputStream::writeInternal (const void* const data, const size_t numBytes) +std::ptrdiff_t FileOutputStream::writeInternal (const void* const data, const size_t numBytes) { - ssize_t result = 0; + std::ptrdiff_t result = 0; if (fileHandle != 0) { @@ -512,7 +512,7 @@ Result RandomAccessFile::nativeRead (void* buffer, ByteCount numBytes, ByteCount { bassert (isOpen ()); - ssize_t bytesRead = ::read (getFD (fileHandle), buffer, numBytes); + std::ptrdiff_t bytesRead = ::read (getFD (fileHandle), buffer, numBytes); if (bytesRead < 0) { @@ -537,7 +537,7 @@ Result RandomAccessFile::nativeWrite (void const* data, ByteCount numBytes, size { bassert (isOpen ()); - ssize_t bytesWritten = ::write (getFD (fileHandle), data, numBytes); + std::ptrdiff_t bytesWritten = ::write (getFD (fileHandle), data, numBytes); // write(3) says that the actual return will be exactly -1 on // error, but we will assume anything negative indicates failure. @@ -627,20 +627,20 @@ File beast_getExecutableFile() } //============================================================================== -int64 File::getBytesFreeOnVolume() const +std::int64_t File::getBytesFreeOnVolume() const { struct statfs buf; if (beast_doStatFS (*this, buf)) - return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user + return (std::int64_t) buf.f_bsize * (std::int64_t) buf.f_bavail; // Note: this returns space available to non-super user return 0; } -int64 File::getVolumeTotalSize() const +std::int64_t File::getVolumeTotalSize() const { struct statfs buf; if (beast_doStatFS (*this, buf)) - return (int64) buf.f_bsize * (int64) buf.f_blocks; + return (std::int64_t) buf.f_bsize * (std::int64_t) buf.f_blocks; return 0; } @@ -723,149 +723,6 @@ String beast_getOutputFromCommand (const String& command) return result; } - -//============================================================================== -#if BEAST_IOS -class InterProcessLock::Pimpl -{ -public: - Pimpl (const String&, int) - : handle (1), refCount (1) // On iOS just fake success.. - { - } - - int handle, refCount; -}; - -#else - -class InterProcessLock::Pimpl -{ -public: - Pimpl (const String& lockName, const int timeOutMillisecs) - : handle (0), refCount (1) - { - #if BEAST_MAC - if (! createLockFile (File ("~/Library/Caches/com.beast.locks").getChildFile (lockName), timeOutMillisecs)) - // Fallback if the user's home folder is on a network drive with no ability to lock.. - createLockFile (File ("/tmp/com.beast.locks").getChildFile (lockName), timeOutMillisecs); - - #else - File tempFolder ("/var/tmp"); - if (! tempFolder.isDirectory()) - tempFolder = "/tmp"; - - createLockFile (tempFolder.getChildFile (lockName), timeOutMillisecs); - #endif - } - - ~Pimpl() - { - closeFile(); - } - - bool createLockFile (const File& file, const int timeOutMillisecs) - { - file.create(); - handle = open (file.getFullPathName().toUTF8(), O_RDWR); - - if (handle != 0) - { - struct flock fl; - zerostruct (fl); - - fl.l_whence = SEEK_SET; - fl.l_type = F_WRLCK; - - const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs; - - for (;;) - { - const int result = fcntl (handle, F_SETLK, &fl); - - if (result >= 0) - return true; - - const int error = errno; - - if (error != EINTR) - { - if (error == EBADF || error == ENOTSUP) - return false; - - if (timeOutMillisecs == 0 - || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime)) - break; - - Thread::sleep (10); - } - } - } - - closeFile(); - return true; // only false if there's a file system error. Failure to lock still returns true. - } - - void closeFile() - { - if (handle != 0) - { - struct flock fl; - zerostruct (fl); - - fl.l_whence = SEEK_SET; - fl.l_type = F_UNLCK; - - while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR)) - {} - - close (handle); - handle = 0; - } - } - - int handle, refCount; -}; -#endif - -InterProcessLock::InterProcessLock (const String& nm) : name (nm) -{ -} - -InterProcessLock::~InterProcessLock() -{ -} - -bool InterProcessLock::enter (const int timeOutMillisecs) -{ - const ScopedLock sl (lock); - - if (pimpl == nullptr) - { - pimpl = new Pimpl (name, timeOutMillisecs); - - if (pimpl->handle == 0) - pimpl = nullptr; - } - else - { - pimpl->refCount++; - } - - return pimpl != nullptr; -} - -void InterProcessLock::exit() -{ - const ScopedLock sl (lock); - - // Trying to release the lock too many times! - bassert (pimpl != nullptr); - - if (pimpl != nullptr && --(pimpl->refCount) == 0) - pimpl = nullptr; -} - //============================================================================== bool DynamicLibrary::open (const String& name) @@ -889,284 +746,4 @@ void* DynamicLibrary::getFunction (const String& functionName) noexcept return handle != nullptr ? dlsym (handle, functionName.toUTF8()) : nullptr; } - - -//============================================================================== -class ChildProcess::ActiveProcess : LeakChecked , public Uncopyable -{ -public: - ActiveProcess (const StringArray& arguments) - : childPID (0), pipeHandle (0), readHandle (0) - { - int pipeHandles[2] = { 0 }; - - if (pipe (pipeHandles) == 0) - { - const pid_t result = fork(); - - if (result < 0) - { - close (pipeHandles[0]); - close (pipeHandles[1]); - } - else if (result == 0) - { - // we're the child process.. - close (pipeHandles[0]); // close the read handle - dup2 (pipeHandles[1], 1); // turns the pipe into stdout - dup2 (pipeHandles[1], 2); // + stderr - close (pipeHandles[1]); - - Array argv; - for (int i = 0; i < arguments.size(); ++i) - if (arguments[i].isNotEmpty()) - argv.add (arguments[i].toUTF8().getAddress()); - - argv.add (nullptr); - - execvp (argv[0], argv.getRawDataPointer()); - exit (-1); - } - else - { - // we're the parent process.. - childPID = result; - pipeHandle = pipeHandles[0]; - close (pipeHandles[1]); // close the write handle - } - } - } - - ~ActiveProcess() - { - if (readHandle != 0) - fclose (readHandle); - - if (pipeHandle != 0) - close (pipeHandle); - } - - bool isRunning() const - { - if (childPID != 0) - { - int childState; - const int pid = waitpid (childPID, &childState, WNOHANG); - return pid == 0 || ! (WIFEXITED (childState) || WIFSIGNALED (childState)); - } - - return false; - } - - int read (void* const dest, const int numBytes) - { - bassert (dest != nullptr); - - #ifdef fdopen - #error // the zlib headers define this function as NULL! - #endif - - if (readHandle == 0 && childPID != 0) - readHandle = fdopen (pipeHandle, "r"); - - if (readHandle != 0) - return (int) fread (dest, 1, (size_t) numBytes, readHandle); - - return 0; - } - - bool killProcess() const - { - return ::kill (childPID, SIGKILL) == 0; - } - - int childPID; - -private: - int pipeHandle; - FILE* readHandle; -}; - -bool ChildProcess::start (const String& command) -{ - return start (StringArray::fromTokens (command, true)); -} - -bool ChildProcess::start (const StringArray& args) -{ - if (args.size() == 0) - return false; - - activeProcess = new ActiveProcess (args); - - if (activeProcess->childPID == 0) - activeProcess = nullptr; - - return activeProcess != nullptr; -} - -bool ChildProcess::isRunning() const -{ - return activeProcess != nullptr && activeProcess->isRunning(); -} - -int ChildProcess::readProcessOutput (void* dest, int numBytes) -{ - return activeProcess != nullptr ? activeProcess->read (dest, numBytes) : 0; -} - -bool ChildProcess::kill() -{ - return activeProcess == nullptr || activeProcess->killProcess(); -} - -//============================================================================== -struct HighResolutionTimer::Pimpl : public Uncopyable -{ - Pimpl (HighResolutionTimer& t) : owner (t), thread (0), shouldStop (false) - { - } - - ~Pimpl() - { - bassert (thread == 0); - } - - void start (int newPeriod) - { - periodMs = newPeriod; - - if (thread == 0) - { - shouldStop = false; - - if (pthread_create (&thread, nullptr, timerThread, this) == 0) - setThreadToRealtime (thread, (uint64) newPeriod); - else - bassertfalse; - } - } - - void stop() - { - if (thread != 0) - { - shouldStop = true; - - while (thread != 0 && thread != pthread_self()) - Thread::yield(); - } - } - - HighResolutionTimer& owner; - int volatile periodMs; - -private: - pthread_t thread; - bool volatile shouldStop; - - static void* timerThread (void* param) - { - #if ! BEAST_ANDROID - int dummy; - pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, &dummy); - #endif - - reinterpret_cast (param)->timerThread(); - return nullptr; - } - - void timerThread() - { - Clock clock (periodMs); - - while (! shouldStop) - { - clock.wait(); - owner.hiResTimerCallback(); - } - - periodMs = 0; - thread = 0; - } - - struct Clock - { - #if BEAST_MAC || BEAST_IOS - Clock (double millis) noexcept - { - mach_timebase_info_data_t timebase; - (void) mach_timebase_info (&timebase); - delta = (((uint64_t) (millis * 1000000.0)) * timebase.numer) / timebase.denom; - time = mach_absolute_time(); - } - - void wait() noexcept - { - time += delta; - mach_wait_until (time); - } - - uint64_t time, delta; - - #elif BEAST_ANDROID || BEAST_BSD - Clock (double millis) noexcept : delta ((uint64) (millis * 1000000)) - { - } - - void wait() noexcept - { - struct timespec t; - t.tv_sec = (time_t) (delta / 1000000000); - t.tv_nsec = (long) (delta % 1000000000); - nanosleep (&t, nullptr); - } - - uint64 delta; - #else - Clock (double millis) noexcept : delta ((uint64) (millis * 1000000)) - { - struct timespec t; - clock_gettime (CLOCK_MONOTONIC, &t); - time = 1000000000 * (int64) t.tv_sec + t.tv_nsec; - } - - void wait() noexcept - { - time += delta; - - struct timespec t; - t.tv_sec = (time_t) (time / 1000000000); - t.tv_nsec = (long) (time % 1000000000); - clock_nanosleep (CLOCK_MONOTONIC, TIMER_ABSTIME, &t, nullptr); - } - - uint64 time, delta; - #endif - }; - - static bool setThreadToRealtime (pthread_t thread, uint64 periodMs) - { - #if BEAST_MAC || BEAST_IOS - thread_time_constraint_policy_data_t policy; - policy.period = (uint32_t) (periodMs * 1000000); - policy.computation = 50000; - policy.constraint = policy.period; - policy.preemptible = true; - - return thread_policy_set (pthread_mach_thread_np (thread), - THREAD_TIME_CONSTRAINT_POLICY, - (thread_policy_t) &policy, - THREAD_TIME_CONSTRAINT_POLICY_COUNT) == KERN_SUCCESS; - - #else - (void) periodMs; - struct sched_param param; - param.sched_priority = sched_get_priority_max (SCHED_RR); - return pthread_setschedparam (thread, SCHED_RR, ¶m) == 0; - - #endif - } -}; - -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/win32_ComSmartPtr.h b/src/beast/modules/beast_core/native/win32_ComSmartPtr.h index f704a8e70b..306267731d 100644 --- a/src/beast/modules/beast_core/native/win32_ComSmartPtr.h +++ b/src/beast/modules/beast_core/native/win32_ComSmartPtr.h @@ -45,8 +45,8 @@ inline GUID uuidFromString (const char* const s) noexcept (s, "%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", &p0, &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10); - GUID g = { p0, (uint16) p1, (uint16) p2, { (uint8) p3, (uint8) p4, (uint8) p5, (uint8) p6, - (uint8) p7, (uint8) p8, (uint8) p9, (uint8) p10 }}; + GUID g = { p0, (std::uint16_t) p1, (std::uint16_t) p2, { (std::uint8_t) p3, (std::uint8_t) p4, (std::uint8_t) p5, (std::uint8_t) p6, + (std::uint8_t) p7, (std::uint8_t) p8, (std::uint8_t) p9, (std::uint8_t) p10 }}; return g; } @@ -165,6 +165,6 @@ public: } }; -} // namespace beast +} // beast #endif // BEAST_WIN32_COMSMARTPTR_H_INCLUDED diff --git a/src/beast/modules/beast_core/native/win32_Files.cpp b/src/beast/modules/beast_core/native/win32_Files.cpp index bb229989e8..87d8bd094a 100644 --- a/src/beast/modules/beast_core/native/win32_Files.cpp +++ b/src/beast/modules/beast_core/native/win32_Files.cpp @@ -36,19 +36,19 @@ namespace WindowsFileHelpers return GetFileAttributes (path.toWideCharPointer()); } - int64 fileTimeToTime (const FILETIME* const ft) + std::int64_t fileTimeToTime (const FILETIME* const ft) { static_bassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails! - return (int64) ((reinterpret_cast (ft)->QuadPart - literal64bit (116444736000000000)) / 10000); + return (std::int64_t) ((reinterpret_cast (ft)->QuadPart - 116444736000000000LL) / 10000); } - FILETIME* timeToFileTime (const int64 time, FILETIME* const ft) noexcept + FILETIME* timeToFileTime (const std::int64_t time, FILETIME* const ft) noexcept { if (time <= 0) return nullptr; - reinterpret_cast (ft)->QuadPart = (ULONGLONG) (time * 10000 + literal64bit (116444736000000000)); + reinterpret_cast (ft)->QuadPart = (ULONGLONG) (time * 10000 + 116444736000000000LL); return ft; } @@ -68,13 +68,13 @@ namespace WindowsFileHelpers return path; } - int64 getDiskSpaceInfo (const String& path, const bool total) + std::int64_t getDiskSpaceInfo (const String& path, const bool total) { ULARGE_INTEGER spc, tot, totFree; if (GetDiskFreeSpaceEx (getDriveFromPath (path).toWideCharPointer(), &spc, &tot, &totFree)) - return total ? (int64) tot.QuadPart - : (int64) spc.QuadPart; + return total ? (std::int64_t) tot.QuadPart + : (std::int64_t) spc.QuadPart; return 0; } @@ -213,7 +213,7 @@ Result File::createDirectoryInternal (const String& fileName) const } //============================================================================== -int64 beast_fileSetPosition (void* handle, int64 pos) +std::int64_t beast_fileSetPosition (void* handle, std::int64_t pos) { LARGE_INTEGER li; li.QuadPart = pos; @@ -279,7 +279,7 @@ void FileOutputStream::closeHandle() CloseHandle ((HANDLE) fileHandle); } -ssize_t FileOutputStream::writeInternal (const void* buffer, size_t numBytes) +std::ptrdiff_t FileOutputStream::writeInternal (const void* buffer, size_t numBytes) { if (fileHandle != nullptr) { @@ -287,7 +287,7 @@ ssize_t FileOutputStream::writeInternal (const void* buffer, size_t numBytes) if (! WriteFile ((HANDLE) fileHandle, buffer, (DWORD) numBytes, &actualNum, 0)) status = WindowsFileHelpers::getResultForLastError(); - return (ssize_t) actualNum; + return (std::ptrdiff_t) actualNum; } return 0; @@ -468,17 +468,17 @@ Result RandomAccessFile::nativeFlush () //============================================================================== -int64 File::getSize() const +std::int64_t File::getSize() const { WIN32_FILE_ATTRIBUTE_DATA attributes; if (GetFileAttributesEx (fullPath.toWideCharPointer(), GetFileExInfoStandard, &attributes)) - return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow; + return (((std::int64_t) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow; return 0; } -void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const +void File::getFileTimesInternal (std::int64_t& modificationTime, std::int64_t& accessTime, std::int64_t& creationTime) const { using namespace WindowsFileHelpers; WIN32_FILE_ATTRIBUTE_DATA attributes; @@ -495,7 +495,7 @@ void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int } } -bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const +bool File::setFileTimesInternal (std::int64_t modificationTime, std::int64_t accessTime, std::int64_t creationTime) const { using namespace WindowsFileHelpers; @@ -564,12 +564,12 @@ int File::getVolumeSerialNumber() const return (int) serialNum; } -int64 File::getBytesFreeOnVolume() const +std::int64_t File::getBytesFreeOnVolume() const { return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false); } -int64 File::getVolumeTotalSize() const +std::int64_t File::getVolumeTotalSize() const { return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true); } @@ -607,7 +607,7 @@ bool File::isOnRemovableDrive() const } //============================================================================== -File BEAST_CALLTYPE File::getSpecialLocation (const SpecialLocationType type) +File File::getSpecialLocation (const SpecialLocationType type) { int csidlType = 0; @@ -751,7 +751,7 @@ public: } bool next (String& filenameFound, - bool* const isDir, bool* const isHidden, int64* const fileSize, + bool* const isDir, bool* const isHidden, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { using namespace WindowsFileHelpers; @@ -775,7 +775,7 @@ public: if (isDir != nullptr) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); if (isHidden != nullptr) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0); if (isReadOnly != nullptr) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0); - if (fileSize != nullptr) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32); + if (fileSize != nullptr) *fileSize = findData.nFileSizeLow + (((std::int64_t) findData.nFileSizeHigh) << 32); if (modTime != nullptr) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime)); if (creationTime != nullptr) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime)); @@ -797,7 +797,7 @@ DirectoryIterator::NativeIterator::~NativeIterator() } bool DirectoryIterator::NativeIterator::next (String& filenameFound, - bool* const isDir, bool* const isHidden, int64* const fileSize, + bool* const isDir, bool* const isHidden, std::int64_t* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly); diff --git a/src/beast/modules/beast_core/native/win32_Network.cpp b/src/beast/modules/beast_core/native/win32_Network.cpp deleted file mode 100644 index 21720a4158..0000000000 --- a/src/beast/modules/beast_core/native/win32_Network.cpp +++ /dev/null @@ -1,67 +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 -{ - -bool Process::openEmailWithAttachments (const String& targetEmailAddress, - const String& emailSubject, - const String& bodyText, - const StringArray& filesToAttach) -{ - DynamicLibrary dll ("MAPI32.dll"); - BEAST_LOAD_WINAPI_FUNCTION (dll, MAPISendMail, mapiSendMail, - ULONG, (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG)) - - if (mapiSendMail == nullptr) - return false; - - MapiMessage message = { 0 }; - message.lpszSubject = (LPSTR) emailSubject.toRawUTF8(); - message.lpszNoteText = (LPSTR) bodyText.toRawUTF8(); - - MapiRecipDesc recip = { 0 }; - recip.ulRecipClass = MAPI_TO; - String targetEmailAddress_ (targetEmailAddress); - if (targetEmailAddress_.isEmpty()) - targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address) - recip.lpszName = (LPSTR) targetEmailAddress_.toRawUTF8(); - message.nRecipCount = 1; - message.lpRecips = &recip; - - HeapBlock files; - files.calloc ((size_t) filesToAttach.size()); - - message.nFileCount = (ULONG) filesToAttach.size(); - message.lpFiles = files; - - for (int i = 0; i < filesToAttach.size(); ++i) - { - files[i].nPosition = (ULONG) -1; - files[i].lpszPathName = (LPSTR) filesToAttach[i].toRawUTF8(); - } - - return mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS; -} - -} // namespace beast diff --git a/src/beast/modules/beast_core/native/win32_Registry.cpp b/src/beast/modules/beast_core/native/win32_Registry.cpp index c2a09204fc..34d9c43790 100644 --- a/src/beast/modules/beast_core/native/win32_Registry.cpp +++ b/src/beast/modules/beast_core/native/win32_Registry.cpp @@ -72,7 +72,7 @@ struct RegistryKeyWrapper : public Uncopyable (DWORD) dataSize) == ERROR_SUCCESS; } - static uint32 getBinaryValue (const String& regValuePath, MemoryBlock& result, DWORD wow64Flags) + static std::uint32_t getBinaryValue (const String& regValuePath, MemoryBlock& result, DWORD wow64Flags) { const RegistryKeyWrapper key (regValuePath, false, wow64Flags); @@ -135,7 +135,7 @@ struct RegistryKeyWrapper : public Uncopyable String valueName; }; -uint32 WindowsRegistry::getBinaryValue (const String& regValuePath, MemoryBlock& result) +std::uint32_t WindowsRegistry::getBinaryValue (const String& regValuePath, MemoryBlock& result) { return RegistryKeyWrapper::getBinaryValue (regValuePath, result, 0); } @@ -161,12 +161,12 @@ bool WindowsRegistry::setValue (const String& regValuePath, const String& value) CharPointer_UTF16::getBytesRequiredFor (value.getCharPointer())); } -bool WindowsRegistry::setValue (const String& regValuePath, const uint32 value) +bool WindowsRegistry::setValue (const String& regValuePath, const std::uint32_t value) { return RegistryKeyWrapper::setValue (regValuePath, REG_DWORD, &value, sizeof (value)); } -bool WindowsRegistry::setValue (const String& regValuePath, const uint64 value) +bool WindowsRegistry::setValue (const String& regValuePath, const std::uint64_t value) { return RegistryKeyWrapper::setValue (regValuePath, REG_QWORD, &value, sizeof (value)); } @@ -216,4 +216,4 @@ bool WindowsRegistry::registerFileAssociation (const String& fileExtension, targetExecutable.getFullPathName() + "," + String (-iconResourceNumber))); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/win32_SystemStats.cpp b/src/beast/modules/beast_core/native/win32_SystemStats.cpp index 56e892aaab..74bb209bd1 100644 --- a/src/beast/modules/beast_core/native/win32_SystemStats.cpp +++ b/src/beast/modules/beast_core/native/win32_SystemStats.cpp @@ -31,8 +31,8 @@ void Logger::outputDebugString (const String& text) //============================================================================== #ifdef BEAST_DLL_BUILD - BEAST_API void* beastDLL_malloc (size_t sz) { return std::malloc (sz); } - BEAST_API void beastDLL_free (void* block) { std::free (block); } + void* beastDLL_malloc (size_t sz) { return std::malloc (sz); } + void beastDLL_free (void* block) { std::free (block); } #endif //============================================================================== @@ -225,9 +225,9 @@ String SystemStats::getEnvironmentVariable (const String& name, const String& de } //============================================================================== -uint32 beast_millisecondsSinceStartup() noexcept +std::uint32_t beast_millisecondsSinceStartup() noexcept { - return (uint32) timeGetTime(); + return (std::uint32_t) timeGetTime(); } //============================================================================== @@ -247,17 +247,17 @@ public: hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond; } - inline int64 getHighResolutionTicks() noexcept + inline std::int64_t getHighResolutionTicks() noexcept { LARGE_INTEGER ticks; QueryPerformanceCounter (&ticks); - const int64 mainCounterAsHiResTicks = (beast_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000; - const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart; + const std::int64_t mainCounterAsHiResTicks = (beast_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000; + const std::int64_t newOffset = mainCounterAsHiResTicks - ticks.QuadPart; // fix for a very obscure PCI hardware bug that can make the counter // sometimes jump forwards by a few seconds.. - const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset); + const std::int64_t offsetDrift = abs64 (newOffset - hiResTicksOffset); if (offsetDrift > (hiResTicksPerSecond >> 1)) hiResTicksOffset = newOffset; @@ -270,22 +270,22 @@ public: return getHighResolutionTicks() * hiResTicksScaleFactor; } - int64 hiResTicksPerSecond, hiResTicksOffset; + std::int64_t hiResTicksPerSecond, hiResTicksOffset; double hiResTicksScaleFactor; }; static HiResCounterHandler hiResCounterHandler; -int64 Time::getHighResolutionTicksPerSecond() noexcept { return hiResCounterHandler.hiResTicksPerSecond; } -int64 Time::getHighResolutionTicks() noexcept { return hiResCounterHandler.getHighResolutionTicks(); } +std::int64_t Time::getHighResolutionTicksPerSecond() noexcept { return hiResCounterHandler.hiResTicksPerSecond; } +std::int64_t Time::getHighResolutionTicks() noexcept { return hiResCounterHandler.getHighResolutionTicks(); } double Time::getMillisecondCounterHiRes() noexcept { return hiResCounterHandler.getMillisecondCounterHiRes(); } //============================================================================== -static int64 beast_getClockCycleCounter() noexcept +static std::int64_t beast_getClockCycleCounter() noexcept { #if BEAST_USE_INTRINSICS // MS intrinsics version... - return (int64) __rdtsc(); + return (std::int64_t) __rdtsc(); #elif BEAST_GCC // GNU inline asm version... @@ -302,7 +302,7 @@ static int64 beast_getClockCycleCounter() noexcept [lo] "m" (lo) : "cc", "eax", "ebx", "ecx", "edx", "memory"); - return (int64) ((((uint64) hi) << 32) | lo); + return (std::int64_t) ((((std::uint64_t) hi) << 32) | lo); #else // MSVC inline asm version... unsigned int hi = 0, lo = 0; @@ -316,14 +316,14 @@ static int64 beast_getClockCycleCounter() noexcept mov hi, edx } - return (int64) ((((uint64) hi) << 32) | lo); + return (std::int64_t) ((((std::uint64_t) hi) << 32) | lo); #endif } int SystemStats::getCpuSpeedInMegaherz() { - const int64 cycles = beast_getClockCycleCounter(); - const uint32 millis = Time::getMillisecondCounter(); + const std::int64_t cycles = beast_getClockCycleCounter(); + const std::uint32_t millis = Time::getMillisecondCounter(); int lastResult = 0; for (;;) @@ -331,8 +331,8 @@ int SystemStats::getCpuSpeedInMegaherz() int n = 1000000; while (--n > 0) {} - const uint32 millisElapsed = Time::getMillisecondCounter() - millis; - const int64 cyclesNow = beast_getClockCycleCounter(); + const std::uint32_t millisElapsed = Time::getMillisecondCounter() - millis; + const std::int64_t cyclesNow = beast_getClockCycleCounter(); if (millisElapsed > 80) { @@ -420,4 +420,4 @@ String SystemStats::getDisplayLanguage() return "en"; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/native/win32_Threads.cpp b/src/beast/modules/beast_core/native/win32_Threads.cpp index bb38984b0f..00b8dc517d 100644 --- a/src/beast/modules/beast_core/native/win32_Threads.cpp +++ b/src/beast/modules/beast_core/native/win32_Threads.cpp @@ -111,7 +111,7 @@ bool beast_isRunningUnderDebugger() return IsDebuggerPresent() != FALSE; } -bool BEAST_CALLTYPE Process::isRunningUnderDebugger() +bool Process::isRunningUnderDebugger() { return beast_isRunningUnderDebugger(); } @@ -184,274 +184,6 @@ void* DynamicLibrary::getFunction (const String& functionName) noexcept : nullptr; } - //============================================================================== -class InterProcessLock::Pimpl -{ -public: - Pimpl (String name, const int timeOutMillisecs) - : handle (0), refCount (1) - { - name = name.replaceCharacter ('\\', '/'); - handle = CreateMutexW (0, TRUE, ("Global\\" + name).toWideCharPointer()); - // Not 100% sure why a global mutex sometimes can't be allocated, but if it fails, fall back to - // a local one. (A local one also sometimes fails on other machines so neither type appears to be - // universally reliable) - if (handle == 0) - handle = CreateMutexW (0, TRUE, ("Local\\" + name).toWideCharPointer()); - - if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS) - { - if (timeOutMillisecs == 0) - { - close(); - return; - } - - switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs)) - { - case WAIT_OBJECT_0: - case WAIT_ABANDONED: - break; - - case WAIT_TIMEOUT: - default: - close(); - break; - } - } - } - - ~Pimpl() - { - close(); - } - - void close() - { - if (handle != 0) - { - ReleaseMutex (handle); - CloseHandle (handle); - handle = 0; - } - } - - HANDLE handle; - int refCount; -}; - -InterProcessLock::InterProcessLock (const String& name_) - : name (name_) -{ -} - -InterProcessLock::~InterProcessLock() -{ -} - -bool InterProcessLock::enter (const int timeOutMillisecs) -{ - const ScopedLock sl (lock); - - if (pimpl == nullptr) - { - pimpl = new Pimpl (name, timeOutMillisecs); - - if (pimpl->handle == 0) - pimpl = nullptr; - } - else - { - pimpl->refCount++; - } - - return pimpl != nullptr; -} - -void InterProcessLock::exit() -{ - const ScopedLock sl (lock); - - // Trying to release the lock too many times! - bassert (pimpl != nullptr); - - if (pimpl != nullptr && --(pimpl->refCount) == 0) - pimpl = nullptr; -} - -//============================================================================== -class ChildProcess::ActiveProcess : LeakChecked , public Uncopyable -{ -public: - ActiveProcess (const String& command) - : ok (false), readPipe (0), writePipe (0) - { - SECURITY_ATTRIBUTES securityAtts = { 0 }; - securityAtts.nLength = sizeof (securityAtts); - securityAtts.bInheritHandle = TRUE; - - if (CreatePipe (&readPipe, &writePipe, &securityAtts, 0) - && SetHandleInformation (readPipe, HANDLE_FLAG_INHERIT, 0)) - { - STARTUPINFOW startupInfo = { 0 }; - startupInfo.cb = sizeof (startupInfo); - startupInfo.hStdError = writePipe; - startupInfo.hStdOutput = writePipe; - startupInfo.dwFlags = STARTF_USESTDHANDLES; - - ok = CreateProcess (nullptr, const_cast (command.toWideCharPointer()), - nullptr, nullptr, TRUE, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT, - nullptr, nullptr, &startupInfo, &processInfo) != FALSE; - } - } - - ~ActiveProcess() - { - if (ok) - { - CloseHandle (processInfo.hThread); - CloseHandle (processInfo.hProcess); - } - - if (readPipe != 0) - CloseHandle (readPipe); - - if (writePipe != 0) - CloseHandle (writePipe); - } - - bool isRunning() const - { - return WaitForSingleObject (processInfo.hProcess, 0) != WAIT_OBJECT_0; - } - - int read (void* dest, int numNeeded) const - { - int total = 0; - - while (ok && numNeeded > 0) - { - DWORD available = 0; - - if (! PeekNamedPipe ((HANDLE) readPipe, nullptr, 0, nullptr, &available, nullptr)) - break; - - const int numToDo = bmin ((int) available, numNeeded); - - if (available == 0) - { - if (! isRunning()) - break; - - Thread::yield(); - } - else - { - DWORD numRead = 0; - if (! ReadFile ((HANDLE) readPipe, dest, numToDo, &numRead, nullptr)) - break; - - total += numRead; - dest = addBytesToPointer (dest, numRead); - numNeeded -= numRead; - } - } - - return total; - } - - bool killProcess() const - { - return TerminateProcess (processInfo.hProcess, 0) != FALSE; - } - - bool ok; - -private: - HANDLE readPipe, writePipe; - PROCESS_INFORMATION processInfo; -}; - -bool ChildProcess::start (const String& command) -{ - activeProcess = new ActiveProcess (command); - - if (! activeProcess->ok) - activeProcess = nullptr; - - return activeProcess != nullptr; -} - -bool ChildProcess::start (const StringArray& args) -{ - return start (args.joinIntoString (" ")); -} - -bool ChildProcess::isRunning() const -{ - return activeProcess != nullptr && activeProcess->isRunning(); -} - -int ChildProcess::readProcessOutput (void* dest, int numBytes) -{ - return activeProcess != nullptr ? activeProcess->read (dest, numBytes) : 0; -} - -bool ChildProcess::kill() -{ - return activeProcess == nullptr || activeProcess->killProcess(); -} - -//============================================================================== -struct HighResolutionTimer::Pimpl : public Uncopyable -{ - Pimpl (HighResolutionTimer& t) noexcept : owner (t), periodMs (0) - { - } - - ~Pimpl() - { - bassert (periodMs == 0); - } - - void start (int newPeriod) - { - if (newPeriod != periodMs) - { - stop(); - periodMs = newPeriod; - - TIMECAPS tc; - if (timeGetDevCaps (&tc, sizeof (tc)) == TIMERR_NOERROR) - { - const int actualPeriod = blimit ((int) tc.wPeriodMin, (int) tc.wPeriodMax, newPeriod); - - timerID = timeSetEvent (actualPeriod, tc.wPeriodMin, callbackFunction, (DWORD_PTR) this, - TIME_PERIODIC | TIME_CALLBACK_FUNCTION | 0x100 /*TIME_KILL_SYNCHRONOUS*/); - } - } - } - - void stop() - { - periodMs = 0; - timeKillEvent (timerID); - } - - HighResolutionTimer& owner; - int periodMs; - -private: - unsigned int timerID; - - static void __stdcall callbackFunction (UINT, UINT, DWORD_PTR userInfo, DWORD_PTR, DWORD_PTR) - { - if (Pimpl* const timer = reinterpret_cast (userInfo)) - if (timer->periodMs != 0) - timer->owner.hiResTimerCallback(); - } -}; - -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/streams/FileInputSource.cpp b/src/beast/modules/beast_core/streams/FileInputSource.cpp index 5248a4d602..2602febdc7 100644 --- a/src/beast/modules/beast_core/streams/FileInputSource.cpp +++ b/src/beast/modules/beast_core/streams/FileInputSource.cpp @@ -43,9 +43,9 @@ InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPat return file.getSiblingFile (relatedItemPath).createInputStream(); } -int64 FileInputSource::hashCode() const +std::int64_t FileInputSource::hashCode() const { - int64 h = file.hashCode(); + std::int64_t h = file.hashCode(); if (useFileTimeInHashGeneration) h ^= file.getLastModificationTime().toMilliseconds(); @@ -53,4 +53,4 @@ int64 FileInputSource::hashCode() const return h; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/streams/FileInputSource.h b/src/beast/modules/beast_core/streams/FileInputSource.h index b0f8dd91d2..77fc835d71 100644 --- a/src/beast/modules/beast_core/streams/FileInputSource.h +++ b/src/beast/modules/beast_core/streams/FileInputSource.h @@ -33,7 +33,7 @@ namespace beast @see InputSource */ -class BEAST_API FileInputSource +class FileInputSource : public InputSource , LeakChecked , public Uncopyable @@ -52,7 +52,7 @@ public: InputStream* createInputStream(); InputStream* createInputStreamFor (const String& relatedItemPath); - int64 hashCode() const; + std::int64_t hashCode() const; private: //============================================================================== @@ -60,6 +60,6 @@ private: bool useFileTimeInHashGeneration; }; -} // namespace beast +} // beast #endif // BEAST_FILEINPUTSOURCE_H_INCLUDED diff --git a/src/beast/modules/beast_core/streams/InputSource.h b/src/beast/modules/beast_core/streams/InputSource.h index 9653fa4999..6b98f15248 100644 --- a/src/beast/modules/beast_core/streams/InputSource.h +++ b/src/beast/modules/beast_core/streams/InputSource.h @@ -36,7 +36,7 @@ namespace beast @see FileInputSource */ -class BEAST_API InputSource : LeakChecked +class InputSource : LeakChecked { public: //============================================================================== @@ -63,9 +63,9 @@ public: /** Returns a hash code that uniquely represents this item. */ - virtual int64 hashCode() const = 0; + virtual std::int64_t hashCode() const = 0; }; -} // namespace beast +} // beast #endif // BEAST_INPUTSOURCE_H_INCLUDED diff --git a/src/beast/modules/beast_core/streams/InputStream.cpp b/src/beast/modules/beast_core/streams/InputStream.cpp index c883c039e5..18601d0ff0 100644 --- a/src/beast/modules/beast_core/streams/InputStream.cpp +++ b/src/beast/modules/beast_core/streams/InputStream.cpp @@ -24,9 +24,9 @@ namespace beast { -int64 InputStream::getNumBytesRemaining() +std::int64_t InputStream::getNumBytesRemaining() { - int64 len = getTotalLength(); + std::int64_t len = getTotalLength(); if (len >= 0) len -= getPosition(); @@ -78,12 +78,12 @@ int InputStream::readInt() return 0; } -int32 InputStream::readInt32() +std::int32_t InputStream::readInt32() { char temp[4]; if (read (temp, 4) == 4) - return (int32) ByteOrder::littleEndianInt (temp); + return (std::int32_t) ByteOrder::littleEndianInt (temp); return 0; } @@ -98,19 +98,19 @@ int InputStream::readIntBigEndian() return 0; } -int32 InputStream::readInt32BigEndian() +std::int32_t InputStream::readInt32BigEndian() { char temp[4]; if (read (temp, 4) == 4) - return (int32) ByteOrder::bigEndianInt (temp); + return (std::int32_t) ByteOrder::bigEndianInt (temp); return 0; } int InputStream::readCompressedInt() { - const uint8 sizeByte = (uint8) readByte(); + const std::uint8_t sizeByte = (std::uint8_t) readByte(); if (sizeByte == 0) return 0; @@ -130,22 +130,22 @@ int InputStream::readCompressedInt() return (sizeByte >> 7) ? -num : num; } -int64 InputStream::readInt64() +std::int64_t InputStream::readInt64() { - union { uint8 asBytes[8]; uint64 asInt64; } n; + union { std::uint8_t asBytes[8]; std::uint64_t asInt64; } n; if (read (n.asBytes, 8) == 8) - return (int64) ByteOrder::swapIfBigEndian (n.asInt64); + return (std::int64_t) ByteOrder::swapIfBigEndian (n.asInt64); return 0; } -int64 InputStream::readInt64BigEndian() +std::int64_t InputStream::readInt64BigEndian() { - union { uint8 asBytes[8]; uint64 asInt64; } n; + union { std::uint8_t asBytes[8]; std::uint64_t asInt64; } n; if (read (n.asBytes, 8) == 8) - return (int64) ByteOrder::swapIfLittleEndian (n.asInt64); + return (std::int64_t) ByteOrder::swapIfLittleEndian (n.asInt64); return 0; } @@ -153,29 +153,29 @@ int64 InputStream::readInt64BigEndian() float InputStream::readFloat() { // the union below relies on these types being the same size... - static_bassert (sizeof (int32) == sizeof (float)); - union { int32 asInt; float asFloat; } n; - n.asInt = (int32) readInt(); + static_bassert (sizeof (std::int32_t) == sizeof (float)); + union { std::int32_t asInt; float asFloat; } n; + n.asInt = (std::int32_t) readInt(); return n.asFloat; } float InputStream::readFloatBigEndian() { - union { int32 asInt; float asFloat; } n; - n.asInt = (int32) readIntBigEndian(); + union { std::int32_t asInt; float asFloat; } n; + n.asInt = (std::int32_t) readIntBigEndian(); return n.asFloat; } double InputStream::readDouble() { - union { int64 asInt; double asDouble; } n; + union { std::int64_t asInt; double asDouble; } n; n.asInt = readInt64(); return n.asDouble; } double InputStream::readDoubleBigEndian() { - union { int64 asInt; double asDouble; } n; + union { std::int64_t asInt; double asDouble; } n; n.asInt = readInt64BigEndian(); return n.asDouble; } @@ -212,7 +212,7 @@ String InputStream::readNextLine() if (data[i] == '\r') { - const int64 lastPos = getPosition(); + const std::int64_t lastPos = getPosition(); if (readByte() != '\n') setPosition (lastPos); @@ -230,7 +230,7 @@ String InputStream::readNextLine() return String::fromUTF8 (data, (int) i); } -int InputStream::readIntoMemoryBlock (MemoryBlock& block, ssize_t numBytes) +int InputStream::readIntoMemoryBlock (MemoryBlock& block, std::ptrdiff_t numBytes) { MemoryOutputStream mo (block, true); return mo.writeFromInputStream (*this, numBytes); @@ -244,15 +244,15 @@ String InputStream::readEntireStreamAsString() } //============================================================================== -void InputStream::skipNextBytes (int64 numBytesToSkip) +void InputStream::skipNextBytes (std::int64_t numBytesToSkip) { if (numBytesToSkip > 0) { - const int skipBufferSize = (int) bmin (numBytesToSkip, (int64) 16384); + const int skipBufferSize = (int) bmin (numBytesToSkip, (std::int64_t) 16384); HeapBlock temp ((size_t) skipBufferSize); while (numBytesToSkip > 0 && ! isExhausted()) - numBytesToSkip -= read (temp, (int) bmin (numBytesToSkip, (int64) skipBufferSize)); + numBytesToSkip -= read (temp, (int) bmin (numBytesToSkip, (std::int64_t) skipBufferSize)); } } @@ -268,10 +268,10 @@ template <> short InputStream::readType () { return readShort (); } template <> -int32 InputStream::readType () { return readInt32 (); } +std::int32_t InputStream::readType () { return readInt32 (); } template <> -int64 InputStream::readType () { return readInt64 (); } +std::int64_t InputStream::readType () { return readInt64 (); } template <> unsigned char InputStream::readType () { return static_cast (readByte ()); } @@ -280,10 +280,10 @@ template <> unsigned short InputStream::readType () { return static_cast (readShort ()); } template <> -uint32 InputStream::readType () { return static_cast (readInt32 ()); } +std::uint32_t InputStream::readType () { return static_cast (readInt32 ()); } template <> -uint64 InputStream::readType () { return static_cast (readInt64 ()); } +std::uint64_t InputStream::readType () { return static_cast (readInt64 ()); } template <> float InputStream::readType () { return readFloat (); } @@ -300,10 +300,10 @@ template <> short InputStream::readTypeBigEndian () { return readShortBigEndian (); } template <> -int32 InputStream::readTypeBigEndian () { return readInt32BigEndian (); } +std::int32_t InputStream::readTypeBigEndian () { return readInt32BigEndian (); } template <> -int64 InputStream::readTypeBigEndian () { return readInt64BigEndian (); } +std::int64_t InputStream::readTypeBigEndian () { return readInt64BigEndian (); } template <> unsigned char InputStream::readTypeBigEndian () { return static_cast (readByte ()); } @@ -312,10 +312,10 @@ template <> unsigned short InputStream::readTypeBigEndian () { return static_cast (readShortBigEndian ()); } template <> -uint32 InputStream::readTypeBigEndian () { return static_cast (readInt32BigEndian ()); } +std::uint32_t InputStream::readTypeBigEndian () { return static_cast (readInt32BigEndian ()); } template <> -uint64 InputStream::readTypeBigEndian () { return static_cast (readInt64BigEndian ()); } +std::uint64_t InputStream::readTypeBigEndian () { return static_cast (readInt64BigEndian ()); } template <> float InputStream::readTypeBigEndian () { return readFloatBigEndian (); } @@ -323,4 +323,4 @@ float InputStream::readTypeBigEndian () { return readFloatBigEndian (); template <> double InputStream::readTypeBigEndian () { return readDoubleBigEndian (); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/streams/InputStream.h b/src/beast/modules/beast_core/streams/InputStream.h index 4ca6869510..ff6750ebc5 100644 --- a/src/beast/modules/beast_core/streams/InputStream.h +++ b/src/beast/modules/beast_core/streams/InputStream.h @@ -37,7 +37,7 @@ class MemoryBlock; @see OutputStream, FileInputStream */ -class BEAST_API InputStream +class InputStream : public Uncopyable , LeakChecked { @@ -55,13 +55,13 @@ public: @see getNumBytesRemaining */ - virtual int64 getTotalLength() = 0; + virtual std::int64_t getTotalLength() = 0; /** Returns the number of bytes available for reading, or a negative value if the remaining length is not known. @see getTotalLength */ - int64 getNumBytesRemaining(); + std::int64_t getNumBytesRemaining(); /** Returns true if the stream has no more data to read. */ virtual bool isExhausted() = 0; @@ -113,8 +113,8 @@ public: virtual short readShort(); // VFALCO TODO Implement these functions - //virtual int16 readInt16 (); - //virtual uint16 readUInt16 (); + //virtual std::int16_t readInt16 (); + //virtual std::uint16_t readUInt16 (); /** Reads two bytes from the stream as a little-endian 16-bit value. @@ -135,11 +135,11 @@ public: @see OutputStream::writeInt, readIntBigEndian */ - virtual int32 readInt32(); + virtual std::int32_t readInt32(); // VFALCO TODO Implement these functions - //virtual int16 readInt16BigEndian (); - //virtual uint16 readUInt16BigEndian (); + //virtual std::int16_t readInt16BigEndian (); + //virtual std::uint16_t readUInt16BigEndian (); // DEPRECATED, assumes sizeof(int) == 4! virtual int readInt(); @@ -153,7 +153,7 @@ public: @see OutputStream::writeIntBigEndian, readInt */ - virtual int32 readInt32BigEndian(); + virtual std::int32_t readInt32BigEndian(); // DEPRECATED, assumes sizeof(int) == 4! virtual int readIntBigEndian(); @@ -167,7 +167,7 @@ public: @see OutputStream::writeInt64, readInt64BigEndian */ - virtual int64 readInt64(); + virtual std::int64_t readInt64(); /** Reads eight bytes from the stream as a big-endian 64-bit value. @@ -178,7 +178,7 @@ public: @see OutputStream::writeInt64BigEndian, readInt64 */ - virtual int64 readInt64BigEndian(); + virtual std::int64_t readInt64BigEndian(); /** Reads four bytes as a 32-bit floating point value. @@ -202,7 +202,7 @@ public: /** Reads eight bytes as a 64-bit floating point value. - The raw 64-bit encoding of the double is read from the stream as a little-endian int64. + The raw 64-bit encoding of the double is read from the stream as a little-endian std::int64_t. If the stream is exhausted partway through reading the bytes, this will return zero. @@ -212,7 +212,7 @@ public: /** Reads eight bytes as a 64-bit floating point value. - The raw 64-bit encoding of the double is read from the stream as a big-endian int64. + The raw 64-bit encoding of the double is read from the stream as a big-endian std::int64_t. If the stream is exhausted partway through reading the bytes, this will return zero. @@ -318,14 +318,14 @@ public: @returns the number of bytes that were added to the memory block */ virtual int readIntoMemoryBlock (MemoryBlock& destBlock, - ssize_t maxNumBytesToRead = -1); + std::ptrdiff_t maxNumBytesToRead = -1); //============================================================================== /** Returns the offset of the next byte that will be read from the stream. @see setPosition */ - virtual int64 getPosition() = 0; + virtual std::int64_t getPosition() = 0; /** Tries to move the current read position of the stream. @@ -339,7 +339,7 @@ public: @returns true if the stream manages to reposition itself correctly @see getPosition */ - virtual bool setPosition (int64 newPosition) = 0; + virtual bool setPosition (std::int64_t newPosition) = 0; /** Reads and discards a number of bytes from the stream. @@ -347,7 +347,7 @@ public: class will just keep reading data until the requisite number of bytes have been done. */ - virtual void skipNextBytes (int64 numBytesToSkip); + virtual void skipNextBytes (std::int64_t numBytesToSkip); protected: @@ -355,6 +355,6 @@ protected: InputStream() noexcept {} }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/streams/MemoryOutputStream.cpp b/src/beast/modules/beast_core/streams/MemoryOutputStream.cpp index 34005a8029..fe817593c1 100644 --- a/src/beast/modules/beast_core/streams/MemoryOutputStream.cpp +++ b/src/beast/modules/beast_core/streams/MemoryOutputStream.cpp @@ -77,7 +77,7 @@ void MemoryOutputStream::reset() noexcept char* MemoryOutputStream::prepareToWrite (size_t numBytes) { - bassert ((ssize_t) numBytes >= 0); + bassert ((std::ptrdiff_t) numBytes >= 0); size_t storageNeeded = position + numBytes; char* data; @@ -119,7 +119,7 @@ bool MemoryOutputStream::write (const void* const buffer, size_t howMany) return false; } -bool MemoryOutputStream::writeRepeatedByte (uint8 byte, size_t howMany) +bool MemoryOutputStream::writeRepeatedByte (std::uint8_t byte, size_t howMany) { if (howMany == 0) return true; @@ -160,9 +160,9 @@ const void* MemoryOutputStream::getData() const noexcept return blockToUse->getData(); } -bool MemoryOutputStream::setPosition (int64 newPosition) +bool MemoryOutputStream::setPosition (std::int64_t newPosition) { - if (newPosition <= (int64) size) + if (newPosition <= (std::int64_t) size) { // ok to seek backwards position = blimit ((size_t) 0, size, (size_t) newPosition); @@ -173,10 +173,10 @@ bool MemoryOutputStream::setPosition (int64 newPosition) return false; } -int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite) +int MemoryOutputStream::writeFromInputStream (InputStream& source, std::int64_t maxNumBytesToWrite) { // before writing from an input, see if we can preallocate to make it more efficient.. - int64 availableData = source.getTotalLength() - source.getPosition(); + std::int64_t availableData = source.getTotalLength() - source.getPosition(); if (availableData > 0) { @@ -201,7 +201,7 @@ String MemoryOutputStream::toString() const return String::createStringFromData (getData(), (int) getDataSize()); } -OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead) +OutputStream& operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead) { const size_t dataSize = streamToRead.getDataSize(); @@ -211,4 +211,4 @@ OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const MemoryOutpu return stream; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/streams/MemoryOutputStream.h b/src/beast/modules/beast_core/streams/MemoryOutputStream.h index 80514f27ad..f4c7356b6b 100644 --- a/src/beast/modules/beast_core/streams/MemoryOutputStream.h +++ b/src/beast/modules/beast_core/streams/MemoryOutputStream.h @@ -41,7 +41,7 @@ namespace beast The data that was written into the stream can then be accessed later as a contiguous block of memory. */ -class BEAST_API MemoryOutputStream +class MemoryOutputStream : public OutputStream , LeakChecked { @@ -121,10 +121,10 @@ public: void flush(); bool write (const void*, size_t) override; - int64 getPosition() override { return position; } - bool setPosition (int64) override; - int writeFromInputStream (InputStream&, int64 maxNumBytesToWrite) override; - bool writeRepeatedByte (uint8 byte, size_t numTimesToRepeat) override; + std::int64_t getPosition() override { return position; } + bool setPosition (std::int64_t) override; + int writeFromInputStream (InputStream&, std::int64_t maxNumBytesToWrite) override; + bool writeRepeatedByte (std::uint8_t byte, size_t numTimesToRepeat) override; private: void trimExternalBlockSize(); @@ -138,8 +138,8 @@ private: }; /** Copies all the data that has been written to a MemoryOutputStream into another stream. */ -OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead); +OutputStream& operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead); -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/streams/OutputStream.cpp b/src/beast/modules/beast_core/streams/OutputStream.cpp index af70c88dcf..80d051f9a8 100644 --- a/src/beast/modules/beast_core/streams/OutputStream.cpp +++ b/src/beast/modules/beast_core/streams/OutputStream.cpp @@ -75,7 +75,7 @@ bool OutputStream::writeByte (char byte) return write (&byte, 1); } -bool OutputStream::writeRepeatedByte (uint8 byte, size_t numTimesToRepeat) +bool OutputStream::writeRepeatedByte (std::uint8_t byte, size_t numTimesToRepeat) { for (size_t i = 0; i < numTimesToRepeat; ++i) if (! writeByte ((char) byte)) @@ -96,11 +96,11 @@ bool OutputStream::writeShortBigEndian (short value) return write (&v, 2); } -bool OutputStream::writeInt32 (int32 value) +bool OutputStream::writeInt32 (std::int32_t value) { - static_bassert (sizeof (int32) == 4); + static_bassert (sizeof (std::int32_t) == 4); - const unsigned int v = ByteOrder::swapIfBigEndian ((uint32) value); + const unsigned int v = ByteOrder::swapIfBigEndian ((std::uint32_t) value); return write (&v, 4); } @@ -114,8 +114,8 @@ bool OutputStream::writeInt (int value) bool OutputStream::writeInt32BigEndian (int value) { - static_bassert (sizeof (int32) == 4); - const uint32 v = ByteOrder::swapIfLittleEndian ((uint32) value); + static_bassert (sizeof (std::int32_t) == 4); + const std::uint32_t v = ByteOrder::swapIfLittleEndian ((std::uint32_t) value); return write (&v, 4); } @@ -131,16 +131,16 @@ bool OutputStream::writeCompressedInt (int value) unsigned int un = (value < 0) ? (unsigned int) -value : (unsigned int) value; - uint8 data[5]; + std::uint8_t data[5]; int num = 0; while (un > 0) { - data[++num] = (uint8) un; + data[++num] = (std::uint8_t) un; un >>= 8; } - data[0] = (uint8) num; + data[0] = (std::uint8_t) num; if (value < 0) data[0] |= 0x80; @@ -148,15 +148,15 @@ bool OutputStream::writeCompressedInt (int value) return write (data, (size_t) num + 1); } -bool OutputStream::writeInt64 (int64 value) +bool OutputStream::writeInt64 (std::int64_t value) { - const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value); + const std::uint64_t v = ByteOrder::swapIfBigEndian ((std::uint64_t) value); return write (&v, 8); } -bool OutputStream::writeInt64BigEndian (int64 value) +bool OutputStream::writeInt64BigEndian (std::int64_t value) { - const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value); + const std::uint64_t v = ByteOrder::swapIfLittleEndian ((std::uint64_t) value); return write (&v, 8); } @@ -176,14 +176,14 @@ bool OutputStream::writeFloatBigEndian (float value) bool OutputStream::writeDouble (double value) { - union { int64 asInt; double asDouble; } n; + union { std::int64_t asInt; double asDouble; } n; n.asDouble = value; return writeInt64 (n.asInt); } bool OutputStream::writeDoubleBigEndian (double value) { - union { int64 asInt; double asDouble; } n; + union { std::int64_t asInt; double asDouble; } n; n.asDouble = value; return writeInt64BigEndian (n.asInt); } @@ -264,17 +264,17 @@ bool OutputStream::writeText (const String& text, const bool asUTF16, return true; } -int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite) +int OutputStream::writeFromInputStream (InputStream& source, std::int64_t numBytesToWrite) { if (numBytesToWrite < 0) - numBytesToWrite = std::numeric_limits::max(); + numBytesToWrite = std::numeric_limits::max(); int numWritten = 0; while (numBytesToWrite > 0) { char buffer [8192]; - const int num = source.read (buffer, (int) bmin (numBytesToWrite, (int64) sizeof (buffer))); + const int num = source.read (buffer, (int) bmin (numBytesToWrite, (std::int64_t) sizeof (buffer))); if (num <= 0) break; @@ -295,34 +295,34 @@ void OutputStream::setNewLineString (const String& newLineString_) } //============================================================================== -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const int number) +OutputStream& operator<< (OutputStream& stream, const int number) { return stream << String (number); } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const int64 number) +OutputStream& operator<< (OutputStream& stream, const std::int64_t number) { return stream << String (number); } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const double number) +OutputStream& operator<< (OutputStream& stream, const double number) { return stream << String (number); } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const char character) +OutputStream& operator<< (OutputStream& stream, const char character) { stream.writeByte (character); return stream; } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const char* const text) +OutputStream& operator<< (OutputStream& stream, const char* const text) { stream.write (text, strlen (text)); return stream; } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data) +OutputStream& operator<< (OutputStream& stream, const MemoryBlock& data) { if (data.getSize() > 0) stream.write (data.getData(), data.getSize()); @@ -330,7 +330,7 @@ BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const M return stream; } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead) +OutputStream& operator<< (OutputStream& stream, const File& fileToRead) { FileInputStream in (fileToRead); @@ -340,13 +340,13 @@ BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const F return stream; } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, InputStream& streamToRead) +OutputStream& operator<< (OutputStream& stream, InputStream& streamToRead) { stream.writeFromInputStream (streamToRead, -1); return stream; } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const NewLine&) +OutputStream& operator<< (OutputStream& stream, const NewLine&) { return stream << stream.getNewLineString(); } @@ -357,68 +357,68 @@ BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const N // definition linker errors, even with the inline keyword! template <> -BEAST_API bool OutputStream::writeType (char v) { return writeByte (v); } +bool OutputStream::writeType (char v) { return writeByte (v); } template <> -BEAST_API bool OutputStream::writeType (short v) { return writeShort (v); } +bool OutputStream::writeType (short v) { return writeShort (v); } template <> -BEAST_API bool OutputStream::writeType (int32 v) { return writeInt32 (v); } +bool OutputStream::writeType (std::int32_t v) { return writeInt32 (v); } template <> -BEAST_API bool OutputStream::writeType (int64 v) { return writeInt64 (v); } +bool OutputStream::writeType (std::int64_t v) { return writeInt64 (v); } template <> -BEAST_API bool OutputStream::writeType (unsigned char v) { return writeByte (static_cast (v)); } +bool OutputStream::writeType (unsigned char v) { return writeByte (static_cast (v)); } template <> -BEAST_API bool OutputStream::writeType (unsigned short v) { return writeShort (static_cast (v)); } +bool OutputStream::writeType (unsigned short v) { return writeShort (static_cast (v)); } template <> -BEAST_API bool OutputStream::writeType (uint32 v) { return writeInt32 (static_cast (v)); } +bool OutputStream::writeType (std::uint32_t v) { return writeInt32 (static_cast (v)); } template <> -BEAST_API bool OutputStream::writeType (uint64 v) { return writeInt64 (static_cast (v)); } +bool OutputStream::writeType (std::uint64_t v) { return writeInt64 (static_cast (v)); } template <> -BEAST_API bool OutputStream::writeType (float v) { return writeFloat (v); } +bool OutputStream::writeType (float v) { return writeFloat (v); } template <> -BEAST_API bool OutputStream::writeType (double v) { return writeDouble (v); } +bool OutputStream::writeType (double v) { return writeDouble (v); } //------------------------------------------------------------------------------ template <> -BEAST_API bool OutputStream::writeTypeBigEndian (char v) { return writeByte (v); } +bool OutputStream::writeTypeBigEndian (char v) { return writeByte (v); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (short v) { return writeShortBigEndian (v); } +bool OutputStream::writeTypeBigEndian (short v) { return writeShortBigEndian (v); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (int32 v) { return writeInt32BigEndian (v); } +bool OutputStream::writeTypeBigEndian (std::int32_t v) { return writeInt32BigEndian (v); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (int64 v) { return writeInt64BigEndian (v); } +bool OutputStream::writeTypeBigEndian (std::int64_t v) { return writeInt64BigEndian (v); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (unsigned char v) { return writeByte (static_cast (v)); } +bool OutputStream::writeTypeBigEndian (unsigned char v) { return writeByte (static_cast (v)); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (unsigned short v) { return writeShortBigEndian (static_cast (v)); } +bool OutputStream::writeTypeBigEndian (unsigned short v) { return writeShortBigEndian (static_cast (v)); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (uint32 v) { return writeInt32BigEndian (static_cast (v)); } +bool OutputStream::writeTypeBigEndian (std::uint32_t v) { return writeInt32BigEndian (static_cast (v)); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (uint64 v) { return writeInt64BigEndian (static_cast (v)); } +bool OutputStream::writeTypeBigEndian (std::uint64_t v) { return writeInt64BigEndian (static_cast (v)); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (float v) { return writeFloatBigEndian (v); } +bool OutputStream::writeTypeBigEndian (float v) { return writeFloatBigEndian (v); } template <> -BEAST_API bool OutputStream::writeTypeBigEndian (double v) { return writeDoubleBigEndian (v); } +bool OutputStream::writeTypeBigEndian (double v) { return writeDoubleBigEndian (v); } -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const String& text) +OutputStream& operator<< (OutputStream& stream, const String& text) { const size_t numBytes = text.getNumBytesAsUTF8(); @@ -435,4 +435,4 @@ BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const S return stream; } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/streams/OutputStream.h b/src/beast/modules/beast_core/streams/OutputStream.h index 1a35622e95..eb790a1a66 100644 --- a/src/beast/modules/beast_core/streams/OutputStream.h +++ b/src/beast/modules/beast_core/streams/OutputStream.h @@ -40,7 +40,7 @@ class File; @see InputStream, MemoryOutputStream, FileOutputStream */ -class BEAST_API OutputStream : public Uncopyable +class OutputStream : public Uncopyable { protected: //============================================================================== @@ -66,13 +66,13 @@ public: @see getPosition */ - virtual bool setPosition (int64 newPosition) = 0; + virtual bool setPosition (std::int64_t newPosition) = 0; /** Returns the stream's current position. @see setPosition */ - virtual int64 getPosition() = 0; + virtual std::int64_t getPosition() = 0; //============================================================================== /** Writes a block of data to the stream. @@ -120,7 +120,7 @@ public: @returns false if the write operation fails for some reason @see InputStream::readInt */ - virtual bool writeInt32 (int32 value); + virtual bool writeInt32 (std::int32_t value); // DEPRECATED, assumes sizeof (int) == 4! virtual bool writeInt (int value); @@ -129,7 +129,7 @@ public: @returns false if the write operation fails for some reason @see InputStream::readIntBigEndian */ - virtual bool writeInt32BigEndian (int32 value); + virtual bool writeInt32BigEndian (std::int32_t value); // DEPRECATED, assumes sizeof (int) == 4! virtual bool writeIntBigEndian (int value); @@ -138,13 +138,13 @@ public: @returns false if the write operation fails for some reason @see InputStream::readInt64 */ - virtual bool writeInt64 (int64 value); + virtual bool writeInt64 (std::int64_t value); /** Writes a 64-bit integer to the stream in a big-endian byte order. @returns false if the write operation fails for some reason @see InputStream::readInt64BigEndian */ - virtual bool writeInt64BigEndian (int64 value); + virtual bool writeInt64BigEndian (std::int64_t value); /** Writes a 32-bit floating point value to the stream in a binary format. The binary 32-bit encoding of the float is written as a little-endian int. @@ -194,7 +194,7 @@ public: /** Writes a byte to the output stream a given number of times. @returns false if the write operation fails for some reason */ - virtual bool writeRepeatedByte (uint8 byte, size_t numTimesToRepeat); + virtual bool writeRepeatedByte (std::uint8_t byte, size_t numTimesToRepeat); /** Writes a condensed binary encoding of a 32-bit integer. @@ -245,7 +245,7 @@ public: is exhausted) @returns the number of bytes written */ - virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite); + virtual int writeFromInputStream (InputStream& source, std::int64_t maxNumBytesToWrite); //============================================================================== /** Sets the string that will be written to the stream when the writeNewLine() @@ -264,28 +264,28 @@ private: //============================================================================== /** Writes a number to a stream as 8-bit characters in the default system encoding. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, int number); +OutputStream& operator<< (OutputStream& stream, int number); /** Writes a number to a stream as 8-bit characters in the default system encoding. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, int64 number); +OutputStream& operator<< (OutputStream& stream, std::int64_t number); /** Writes a number to a stream as 8-bit characters in the default system encoding. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, double number); +OutputStream& operator<< (OutputStream& stream, double number); /** Writes a character to a stream. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, char character); +OutputStream& operator<< (OutputStream& stream, char character); /** Writes a null-terminated text string to a stream. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const char* text); +OutputStream& operator<< (OutputStream& stream, const char* text); /** Writes a block of data from a MemoryBlock to a stream. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data); +OutputStream& operator<< (OutputStream& stream, const MemoryBlock& data); /** Writes the contents of a file to a stream. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead); +OutputStream& operator<< (OutputStream& stream, const File& fileToRead); /** Writes the complete contents of an input stream to an output stream. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, InputStream& streamToRead); +OutputStream& operator<< (OutputStream& stream, InputStream& streamToRead); /** Writes a new-line to a stream. You can use the predefined symbol 'newLine' to invoke this, e.g. @@ -294,11 +294,11 @@ BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, InputSt @endcode @see OutputStream::setNewLineString */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const NewLine&); +OutputStream& operator<< (OutputStream& stream, const NewLine&); /** Writes a string to an OutputStream as UTF8. */ -BEAST_API OutputStream& BEAST_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite); +OutputStream& operator<< (OutputStream& stream, const String& stringToWrite); -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/system/Functional.h b/src/beast/modules/beast_core/system/Functional.h index eed61a9a19..faac1e13a0 100644 --- a/src/beast/modules/beast_core/system/Functional.h +++ b/src/beast/modules/beast_core/system/Functional.h @@ -376,6 +376,6 @@ using namespace placeholders; #endif -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/system/SystemStats.cpp b/src/beast/modules/beast_core/system/SystemStats.cpp index c9caeddf52..be7feddd0f 100644 --- a/src/beast/modules/beast_core/system/SystemStats.cpp +++ b/src/beast/modules/beast_core/system/SystemStats.cpp @@ -28,15 +28,15 @@ String SystemStats::getBeastVersion() { // Some basic tests, to keep an eye on things and make sure these types work ok // on all platforms. Let me know if any of these assertions fail on your system! - static_bassert (sizeof (pointer_sized_int) == sizeof (void*)); - static_bassert (sizeof (int8) == 1); - static_bassert (sizeof (uint8) == 1); - static_bassert (sizeof (int16) == 2); - static_bassert (sizeof (uint16) == 2); - static_bassert (sizeof (int32) == 4); - static_bassert (sizeof (uint32) == 4); - static_bassert (sizeof (int64) == 8); - static_bassert (sizeof (uint64) == 8); + static_bassert (sizeof (std::intptr_t) == sizeof (void*)); + static_bassert (sizeof (std::int8_t) == 1); + static_bassert (sizeof (std::uint8_t) == 1); + static_bassert (sizeof (std::int16_t) == 2); + static_bassert (sizeof (std::uint16_t) == 2); + static_bassert (sizeof (std::int32_t) == 4); + static_bassert (sizeof (std::uint32_t) == 4); + static_bassert (sizeof (std::int64_t) == 8); + static_bassert (sizeof (std::uint64_t) == 8); return "Beast v" BEAST_STRINGIFY(BEAST_MAJOR_VERSION) "." BEAST_STRINGIFY(BEAST_MINOR_VERSION) @@ -107,7 +107,7 @@ String SystemStats::getStackBacktrace() if (::SymGetModuleInfo64 (process, symbol->ModBase, &moduleInfo)) result << moduleInfo.ModuleName << ": "; - result << symbol->Name << " + 0x" << String::toHexString ((int64) displacement) << newLine; + result << symbol->Name << " + 0x" << String::toHexString ((std::int64_t) displacement) << newLine; } } @@ -162,4 +162,4 @@ void SystemStats::setApplicationCrashHandler (CrashHandlerFunction handler) #endif } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/system/SystemStats.h b/src/beast/modules/beast_core/system/SystemStats.h index d0b7682a4d..3673f1d28b 100644 --- a/src/beast/modules/beast_core/system/SystemStats.h +++ b/src/beast/modules/beast_core/system/SystemStats.h @@ -31,7 +31,7 @@ namespace beast /** Contains methods for finding out about the current hardware and OS configuration. */ -class BEAST_API SystemStats : public Uncopyable +class SystemStats : public Uncopyable { public: //============================================================================== @@ -180,6 +180,6 @@ private: SystemStats(); }; -} // namespace beast +} // beast #endif // BEAST_SYSTEMSTATS_H_INCLUDED diff --git a/src/beast/modules/beast_core/text/LexicalCast.cpp b/src/beast/modules/beast_core/text/LexicalCast.cpp index cc5d1d703c..f3c2e723ef 100644 --- a/src/beast/modules/beast_core/text/LexicalCast.cpp +++ b/src/beast/modules/beast_core/text/LexicalCast.cpp @@ -107,7 +107,7 @@ public: void run() { - int64 const seedValue = 50; + std::int64_t const seedValue = 50; Random r (seedValue); @@ -115,10 +115,10 @@ public: testIntegers (r); testIntegers (r); testIntegers (r); - testIntegers (r); - testIntegers (r); - testIntegers (r); - testIntegers (r); + testIntegers (r); + testIntegers (r); + testIntegers (r); + testIntegers (r); } }; diff --git a/src/beast/modules/beast_core/text/LexicalCast.h b/src/beast/modules/beast_core/text/LexicalCast.h index 3995191053..689db187bb 100644 --- a/src/beast/modules/beast_core/text/LexicalCast.h +++ b/src/beast/modules/beast_core/text/LexicalCast.h @@ -35,7 +35,7 @@ struct LexicalCastUtilities if (0 == std::distance (begin, end)) return false; - uint64 accum = 0; + std::uint64_t accum = 0; InputIterator it = begin; // process sign @@ -53,23 +53,23 @@ struct LexicalCastUtilities return false; // calc max of abs value - uint64 max; + std::uint64_t max; if (negative) - max = static_cast ( - -(static_cast (std::numeric_limits ::min ()))); + max = static_cast ( + -(static_cast (std::numeric_limits ::min ()))); else max = std::numeric_limits ::max (); // process digits while (end != it) { - uint64 const digit = static_cast ( + std::uint64_t const digit = static_cast ( s_digitTable [static_cast (*it++)]); if (0xFF == digit) return false; - uint64 const overflow = (max - digit) / 10; + std::uint64_t const overflow = (max - digit) / 10; if (accum > overflow) return false; @@ -95,20 +95,20 @@ struct LexicalCastUtilities if (0 == std::distance (begin, end)) return false; - uint64 accum = 0; + std::uint64_t accum = 0; InputIterator it = begin; - uint64 const max = std::numeric_limits ::max (); + std::uint64_t const max = std::numeric_limits ::max (); // process digits while (end != it) { - uint64 const digit = static_cast ( + std::uint64_t const digit = static_cast ( s_digitTable [static_cast (*it++)]); if (0xFF == digit) return false; - uint64 const overflow = (max - digit) / 10; + std::uint64_t const overflow = (max - digit) / 10; if (accum > overflow) return false; @@ -143,8 +143,8 @@ struct LexicalCast bool operator() (String& out, unsigned int in) const { out = String (in); return true; } bool operator() (String& out, short in) const { out = String (in); return true; } bool operator() (String& out, unsigned short in) const { out = String (in); return true; } - bool operator() (String& out, int64 in) const { out = String (in); return true; } - bool operator() (String& out, uint64 in) const { out = String (in); return true; } + bool operator() (String& out, std::int64_t in) const { out = String (in); return true; } + bool operator() (String& out, std::uint64_t in) const { out = String (in); return true; } bool operator() (String& out, float in) const { out = String (in); return true; } bool operator() (String& out, double in) const { out = String (in); return true; } }; @@ -155,10 +155,10 @@ struct LexicalCast { bool operator() (int& out, String const& in) const { std::string const& s (in.toStdString ()); return LexicalCastUtilities::parseSigned (out, s.begin (), s.end ()); } bool operator() (short& out, String const& in) const { std::string const& s (in.toStdString ()); return LexicalCastUtilities::parseSigned (out, s.begin (), s.end ()); } - bool operator() (int64& out, String const& in) const { std::string const& s (in.toStdString ()); return LexicalCastUtilities::parseSigned (out, s.begin (), s.end ()); } + bool operator() (std::int64_t& out, String const& in) const { std::string const& s (in.toStdString ()); return LexicalCastUtilities::parseSigned (out, s.begin (), s.end ()); } bool operator() (unsigned int& out, String const& in) const { std::string const& s (in.toStdString ()); return LexicalCastUtilities::parseUnsigned (out, s.begin (), s.end ()); } bool operator() (unsigned short& out, String const& in) const { std::string const& s (in.toStdString ()); return LexicalCastUtilities::parseUnsigned (out, s.begin (), s.end ()); } - bool operator() (uint64& out, String const& in) const { std::string const& s (in.toStdString ()); return LexicalCastUtilities::parseUnsigned (out, s.begin (), s.end ()); } + bool operator() (std::uint64_t& out, String const& in) const { std::string const& s (in.toStdString ()); return LexicalCastUtilities::parseUnsigned (out, s.begin (), s.end ()); } bool operator() (float& out, String const& in) const { bassertfalse; return false; /* UNIMPLEMENTED! */ } bool operator() (double& out, String const& in) const { bassertfalse; return false; /* UNIMPLEMENTED! */ } @@ -282,7 +282,7 @@ Out lexicalCastThrow (In in) if (lexicalCastChecked (out, in)) return out; - Throw (BadLexicalCast (), __FILE__, __LINE__); + throw BadLexicalCast (); return Out (); } @@ -303,6 +303,6 @@ Out lexicalCast (In in, Out defaultValue = Out ()) return defaultValue; } -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/text/StringArray.cpp b/src/beast/modules/beast_core/text/StringArray.cpp index 1d74a40ba4..3a3c06cdbe 100644 --- a/src/beast/modules/beast_core/text/StringArray.cpp +++ b/src/beast/modules/beast_core/text/StringArray.cpp @@ -512,4 +512,4 @@ void StringArray::minimiseStorageOverheads() strings.minimiseStorageOverheads(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/text/StringArray.h b/src/beast/modules/beast_core/text/StringArray.h index c37e24894a..426b98ed42 100644 --- a/src/beast/modules/beast_core/text/StringArray.h +++ b/src/beast/modules/beast_core/text/StringArray.h @@ -24,8 +24,10 @@ #ifndef BEAST_STRINGARRAY_H_INCLUDED #define BEAST_STRINGARRAY_H_INCLUDED -namespace beast -{ +#include "../containers/Array.h" +#include "../threads/CriticalSection.h" + +namespace beast { //============================================================================== /** @@ -33,7 +35,7 @@ namespace beast @see String, StringPairArray */ -class BEAST_API StringArray : LeakChecked +class StringArray : LeakChecked { public: //============================================================================== @@ -407,6 +409,6 @@ private: Array strings; }; -} // namespace beast +} // beast #endif // BEAST_STRINGARRAY_H_INCLUDED diff --git a/src/beast/modules/beast_core/text/StringPairArray.cpp b/src/beast/modules/beast_core/text/StringPairArray.cpp index db1227e170..8ed5639367 100644 --- a/src/beast/modules/beast_core/text/StringPairArray.cpp +++ b/src/beast/modules/beast_core/text/StringPairArray.cpp @@ -146,4 +146,4 @@ void StringPairArray::minimiseStorageOverheads() values.minimiseStorageOverheads(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/text/StringPairArray.h b/src/beast/modules/beast_core/text/StringPairArray.h index 7200e12005..e9edce21ee 100644 --- a/src/beast/modules/beast_core/text/StringPairArray.h +++ b/src/beast/modules/beast_core/text/StringPairArray.h @@ -24,8 +24,10 @@ #ifndef BEAST_STRINGPAIRARRAY_H_INCLUDED #define BEAST_STRINGPAIRARRAY_H_INCLUDED -namespace beast -{ +#include "StringArray.h" +#include "../../../beast/utility/LeakChecked.h" + +namespace beast { //============================================================================== /** @@ -33,7 +35,7 @@ namespace beast @see StringArray */ -class BEAST_API StringPairArray : LeakChecked +class StringPairArray : LeakChecked { public: //============================================================================== @@ -155,6 +157,6 @@ private: bool ignoreCase; }; -} // namespace beast +} // beast #endif // BEAST_STRINGPAIRARRAY_H_INCLUDED diff --git a/src/beast/modules/beast_core/thread/DeadlineTimer.cpp b/src/beast/modules/beast_core/thread/DeadlineTimer.cpp index f96b77a8b8..f544860819 100644 --- a/src/beast/modules/beast_core/thread/DeadlineTimer.cpp +++ b/src/beast/modules/beast_core/thread/DeadlineTimer.cpp @@ -50,7 +50,7 @@ public: { bassert (secondsRecurring >= 0); - LockType::ScopedLockType lock (m_mutex); + std::lock_guard lock (m_mutex); if (timer.m_isActive) { @@ -73,7 +73,7 @@ public: // void deactivate (DeadlineTimer& timer) { - LockType::ScopedLockType lock (m_mutex); + std::lock_guard lock (m_mutex); if (timer.m_isActive) { @@ -96,7 +96,7 @@ public: DeadlineTimer* timer (nullptr); { - LockType::ScopedLockType lock (m_mutex); + std::lock_guard lock (m_mutex); // See if a timer expired if (! m_items.empty ()) @@ -245,4 +245,4 @@ void DeadlineTimer::setRecurringExpiration (double secondsUntilDeadline) m_manager->activate (*this, secondsUntilDeadline, when); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/thread/DeadlineTimer.h b/src/beast/modules/beast_core/thread/DeadlineTimer.h index af4a5f69b2..0d8923868c 100644 --- a/src/beast/modules/beast_core/thread/DeadlineTimer.h +++ b/src/beast/modules/beast_core/thread/DeadlineTimer.h @@ -111,6 +111,6 @@ private: double m_secondsRecurring; // non zero if recurring }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/thread/MutexTraits.h b/src/beast/modules/beast_core/thread/MutexTraits.h index b6ec878e98..f8da2cecba 100644 --- a/src/beast/modules/beast_core/thread/MutexTraits.h +++ b/src/beast/modules/beast_core/thread/MutexTraits.h @@ -75,6 +75,6 @@ struct MutexTraits } }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/thread/TrackedMutex.h b/src/beast/modules/beast_core/thread/TrackedMutex.h deleted file mode 100644 index e41dc0b1d4..0000000000 --- a/src/beast/modules/beast_core/thread/TrackedMutex.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. -*/ -//============================================================================== - -#ifndef BEAST_CORE_THREAD_TRACKEDMUTEX_H_INCLUDED -#define BEAST_CORE_THREAD_TRACKEDMUTEX_H_INCLUDED - -#include "detail/TrackedMutex.h" -#include "detail/ScopedLock.h" - -#include "impl/TrackedMutex.h" -#include "impl/TrackedMutexType.h" -#include "impl/UntrackedMutexType.h" - -#endif diff --git a/src/beast/modules/beast_core/thread/Workers.h b/src/beast/modules/beast_core/thread/Workers.h index ece2b8af13..f20bc35825 100644 --- a/src/beast/modules/beast_core/thread/Workers.h +++ b/src/beast/modules/beast_core/thread/Workers.h @@ -20,8 +20,10 @@ #ifndef BEAST_WORKERS_H_INCLUDED #define BEAST_WORKERS_H_INCLUDED -namespace beast -{ +#include "../system/SystemStats.h" +#include "../../../beast/threads/semaphore.h" + +namespace beast { /** A group of threads that process tasks. */ @@ -142,6 +144,6 @@ private: LockFreeStack m_paused; // holds just paused workers }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/thread/detail/ScopedLock.h b/src/beast/modules/beast_core/thread/detail/ScopedLock.h index 4d3dbc0b67..f4a72d3549 100644 --- a/src/beast/modules/beast_core/thread/detail/ScopedLock.h +++ b/src/beast/modules/beast_core/thread/detail/ScopedLock.h @@ -250,8 +250,8 @@ private: bool m_owns_lock; }; -} // namespace detail +} // detail -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/thread/detail/TrackedMutex.h b/src/beast/modules/beast_core/thread/detail/TrackedMutex.h deleted file mode 100644 index 536a3ff229..0000000000 --- a/src/beast/modules/beast_core/thread/detail/TrackedMutex.h +++ /dev/null @@ -1,101 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CORE_THREAD_DETAIL_TRACKEDMUTEX_H_INCLUDED -#define BEAST_CORE_THREAD_DETAIL_TRACKEDMUTEX_H_INCLUDED - -namespace beast -{ - -class TrackedMutex; - -namespace detail -{ - -struct TrackedMutexBasics -{ - struct PerThreadData; - - typedef List ThreadLockList; - typedef List GlobalThreadList; - - // Retrieve an atomic counter unique to class Object - template - static Atomic & getCounter () noexcept - { - static Atomic counter; - return counter; - } - - template - inline static String createName (String name, - char const* fileName, int lineNumber) - { - return createName (name, fileName, lineNumber, - ++getCounter ()); - } - - static String createName (String name, - char const* fileName, int lineNumber, int instanceNumber = 0); - - struct PerThreadData - : GlobalThreadList::Node - { - PerThreadData (); - - int id; - int refCount; - ThreadLockList list; - CriticalSection mutex; - - TrackedMutex const* blocked; - String threadName; // at the time of the block - String sourceLocation; // at the time of the block - }; - - // This turns the thread local into a POD which will be - // initialized to all zeroes. We use the 'id' flag to - // know to initialize. - // - struct PerThreadDataStorage - { - BEAST_ALIGN(8) - unsigned char bytes [sizeof (PerThreadData)]; - }; - - static Atomic lastThreadId; - - static ThreadLocalValue threadLocal; - - static PerThreadData& getPerThreadData (); - - struct Lists - { - GlobalThreadList allThreads; - }; - - static CriticalSection& getGlobalMutex (); - static Lists& getLists (); -}; - -} // namespace detail - -} // namespace beast - -#endif diff --git a/src/beast/modules/beast_core/thread/impl/TrackedMutex.cpp b/src/beast/modules/beast_core/thread/impl/TrackedMutex.cpp deleted file mode 100644 index 59245d94ca..0000000000 --- a/src/beast/modules/beast_core/thread/impl/TrackedMutex.cpp +++ /dev/null @@ -1,478 +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 detail { - -// Example: -// -// m_mutex[2] @ beast_deadlineTimer.cpp(25) -// -String detail::TrackedMutexBasics::createName (String name, - char const* fileName, int lineNumber, int instanceNumber) -{ - return name + - ((instanceNumber > 1) ? - (String ("[") + String::fromNumber (instanceNumber) + "] (") : " (") + - Debug::getFileNameFromPath (fileName) + "," + - String::fromNumber (lineNumber) + ")"; -} - -Atomic TrackedMutexBasics::lastThreadId; - -ThreadLocalValue TrackedMutexBasics::threadLocal; - -TrackedMutexBasics::PerThreadData::PerThreadData () - : id (++lastThreadId) -{ -} - -TrackedMutexBasics::PerThreadData& TrackedMutexBasics::getPerThreadData () -{ - PerThreadData& thread (*reinterpret_cast (&threadLocal.get ())); - - // Manually call the constructor with placement new if needed - if (! thread.id) - { - new (&thread) PerThreadData (); - bassert (thread.id != 0); - } - - return thread; -} - -CriticalSection& TrackedMutexBasics::getGlobalMutex () -{ - static CriticalSection mutex; - return mutex; -} - -TrackedMutexBasics::Lists& TrackedMutexBasics::getLists () -{ - static Lists lists; - return lists; -} - -//------------------------------------------------------------------------------ - -} // detail - -//============================================================================== - -TrackedMutex::Record::Record (String mutexName, - String threadName, String sourceLocation) - : m_mutexName (mutexName) - , m_threadName (threadName) - , m_sourceLocation (sourceLocation) -{ -} - -TrackedMutex::Record::Record () noexcept -{ -} - -TrackedMutex::Record::Record (Record const& other) noexcept - : m_mutexName (other.m_mutexName) - , m_threadName (other.m_threadName) - , m_sourceLocation (other.m_sourceLocation) -{ -} - -TrackedMutex::Record& TrackedMutex::Record::operator= (Record const& other) noexcept -{ - m_mutexName = other.m_mutexName; - m_threadName = other.m_threadName; - m_sourceLocation = other.m_sourceLocation; - return *this; -} - -bool TrackedMutex::Record::isNull () const noexcept -{ - return m_mutexName == ""; -} - -bool TrackedMutex::Record::isNotNull () const noexcept -{ - return m_mutexName != ""; -} - -TrackedMutex::Record::operator bool() const noexcept -{ - return isNotNull (); -} - -String TrackedMutex::Record::getMutexName () const noexcept -{ - return m_mutexName; -} - -String TrackedMutex::Record::getThreadName () const noexcept -{ - return m_threadName; -} - -String TrackedMutex::Record::getSourceLocation () const noexcept -{ - return m_sourceLocation; -} - -//------------------------------------------------------------------------------ - -TrackedMutex::Agent::Agent (detail::TrackedMutexBasics::PerThreadData* thread) - : m_thread (thread) - , m_threadName (thread->threadName) -{ -} - -TrackedMutex::Agent::Agent () noexcept - : m_thread (nullptr) -{ -} - -TrackedMutex::Agent::Agent (Agent const& other) noexcept - : m_thread (other.m_thread) - , m_threadName (other.m_threadName) - , m_blocked (other.m_blocked) -{ -} - -TrackedMutex::Agent& TrackedMutex::Agent::operator= (Agent const& other) noexcept -{ - m_thread = other.m_thread; - m_threadName = other.m_threadName; - m_blocked = other.m_blocked; - return *this; -} - -bool TrackedMutex::Agent::isNull () const noexcept -{ - return m_thread == nullptr; -} - -bool TrackedMutex::Agent::isNotNull () const noexcept -{ - return m_thread != nullptr; -} - -TrackedMutex::Agent::operator bool() const noexcept -{ - return isNotNull (); -} - -String TrackedMutex::Agent::getThreadName () const noexcept -{ - return m_threadName; -} - -TrackedMutex::Record TrackedMutex::Agent::getBlockedRecord () const noexcept -{ - return m_blocked; -} - -bool TrackedMutex::Agent::getLockedList (Array & output) -{ - bassert (isNotNull ()); - - output.clearQuick (); - - typedef detail::TrackedMutexBasics::ThreadLockList ListType; - - { - CriticalSection::ScopedLockType lock (m_thread->mutex); - - ListType const& list (m_thread->list); - - output.ensureStorageAllocated (list.size ()); - - for (ListType::const_iterator iter = list.begin (); - iter != list.end (); ++iter) - { - TrackedMutex const& mutex = *iter; - { - TrackedMutex::SharedState::ConstAccess state (mutex.m_state); - output.add (state->owner); - } - } - } - - return output.size () > 0; -} - -//------------------------------------------------------------------------------ - -TrackedMutex::State::State () - : thread (nullptr) -{ -} - -//------------------------------------------------------------------------------ - -TrackedMutex::TrackedMutex (String const& name) noexcept - : m_name (name) - , m_count (0) -{ -} - -String TrackedMutex::getName () const noexcept -{ - return m_name; -} - -TrackedMutex::Record TrackedMutex::getOwnerRecord () const noexcept -{ - { - SharedState::ConstAccess state (m_state); - return state->owner; - } -} - -TrackedMutex::Agent TrackedMutex::getOwnerAgent () const noexcept -{ - { - SharedState::ConstAccess state (m_state); - if (state->thread != nullptr) - return Agent (state->thread); - } - - return Agent (); -} - -//------------------------------------------------------------------------------ - -void TrackedMutex::generateGlobalBlockedReport (StringArray& report) -{ - report.clear (); - - { - CriticalSection::ScopedLockType lock ( - detail::TrackedMutexBasics::getGlobalMutex ()); - - typedef detail::TrackedMutexBasics::GlobalThreadList ListType; - - ListType const& list (detail::TrackedMutexBasics::getLists ().allThreads); - - for (ListType::const_iterator iter = list.begin (); iter != list.end (); ++iter) - { - detail::TrackedMutexBasics::PerThreadData const* thread ( - &(*iter)); - - typedef detail::TrackedMutexBasics::ThreadLockList LockedList; - LockedList const& owned (thread->list); - - if (thread->blocked) - { - String s; - s << thread->threadName << " blocked on " << - thread->blocked->getName () << " at " << - thread->sourceLocation; - if (owned.size () > 0) - s << " and owns these locks:"; - report.add (s); - } - else if (owned.size () > 0) - { - String s; - s << thread->threadName << " owns these locks:"; - report.add (s); - } - - if (owned.size () > 0) - { - for (LockedList::const_iterator iter = owned.begin (); iter != owned.end (); ++iter) - { - String s; - TrackedMutex const& mutex (*iter); - TrackedMutex::SharedState::ConstAccess state (mutex.m_state); - s << " " << mutex.getName () << - " from " << state->owner.getSourceLocation (); - report.add (s); - } - } - } - } -} - -//------------------------------------------------------------------------------ - -// Called before we attempt to acquire the mutex. -// -void TrackedMutex::block (char const* fileName, int lineNumber) const noexcept -{ - // Get calling thread data. - detail::TrackedMutexBasics::PerThreadData& thread - (detail::TrackedMutexBasics::getPerThreadData ()); - - ++thread.refCount; - - String const sourceLocation (makeSourceLocation (fileName, lineNumber)); - - { - // Take a global lock. - CriticalSection::ScopedLockType globalLock ( - detail::TrackedMutexBasics::getGlobalMutex ()); - - { - // Take a thread lock. - CriticalSection::ScopedLockType threadLock (thread.mutex); - - // Set the thread's blocked record - thread.blocked = this; - thread.threadName = makeThreadName (thread); - thread.sourceLocation = sourceLocation; - - // Add this thread to threads list. - if (thread.refCount == 1) - detail::TrackedMutexBasics::getLists().allThreads.push_back (thread); - } - } -} - -//------------------------------------------------------------------------------ - -// Called after we already have ownership of the mutex -// -void TrackedMutex::acquired (char const* fileName, int lineNumber) const noexcept -{ - // Retrieve the per-thread data for the calling thread. - detail::TrackedMutexBasics::PerThreadData& thread - (detail::TrackedMutexBasics::getPerThreadData ()); - - // If this goes off it means block() wasn't called. - bassert (thread.refCount > 0); - - ++m_count; - - // Take ownership on the first count. - if (m_count == 1) - { - // Thread is a new owner of the mutex. - String const sourceLocation (makeSourceLocation (fileName, lineNumber)); - String const threadName (makeThreadName (thread)); - - { - // Take a global lock. - CriticalSection::ScopedLockType globalLock ( - detail::TrackedMutexBasics::getGlobalMutex ()); - - { - // Take a state lock. - SharedState::Access state (m_state); - - // Set the mutex ownership record - state->owner = Record (getName (), threadName, sourceLocation); - state->thread = &thread; - - { - // Take a thread lock. - CriticalSection::ScopedLockType threadLock (thread.mutex); - - // Add the mutex to the thread's list. - thread.list.push_back (const_cast (*this)); - - // Unblock the thread record. - thread.blocked = nullptr; - thread.sourceLocation = ""; - } - } - } - } - else - { - // Thread already had ownership of the mutex. - bassert (SharedState::ConstUnlockedAccess (m_state)->thread == &thread); - - // If this goes off it means we counted wrong. - bassert (thread.refCount >= m_count); - } -} - -//------------------------------------------------------------------------------ - -void TrackedMutex::release () const noexcept -{ - // If this goes off it means we don't own the mutex! - bassert (m_count > 0); - - // Retrieve the per-thread data for the calling thread. - detail::TrackedMutexBasics::PerThreadData& thread - (detail::TrackedMutexBasics::getPerThreadData ()); - - // If this goes off it means we counted wrong. - bassert (thread.refCount >= m_count); - - --m_count; - --thread.refCount; - - // Give up ownership when the count drops to zero. - if (m_count == 0) - { - // Take the global mutex - CriticalSection::ScopedLockType globalLock ( - detail::TrackedMutexBasics::getGlobalMutex ()); - - { - // Take the mutex' state lock - SharedState::Access state (m_state); - - // Clear the mutex ownership record - state->owner = Record (); - state->thread = nullptr; - - { - // Take the thread mutex - CriticalSection::ScopedLockType threadLock (thread.mutex); - - // Remove this mutex from the list of the thread's owned locks. - thread.list.erase (thread.list.iterator_to ( - const_cast (*this))); - - // Remove this thread from the threads list. - if (thread.refCount == 0) - { - typedef detail::TrackedMutexBasics::GlobalThreadList ListType; - ListType& list (detail::TrackedMutexBasics::getLists().allThreads); - list.erase (list.iterator_to (thread)); - } - } - } - } -} - -//------------------------------------------------------------------------------ - -String TrackedMutex::makeThreadName ( - detail::TrackedMutexBasics::PerThreadData const& thread) noexcept -{ - String threadName; - Thread const* const currentThread (Thread::getCurrentThread ()); - if (currentThread != nullptr) - threadName = currentThread->getThreadName (); - threadName = threadName + "[" + String::fromNumber (thread.id) + "]"; - return threadName; -} - -String TrackedMutex::makeSourceLocation (char const* fileName, int lineNumber) noexcept -{ - String const sourceLocation (Debug::getFileNameFromPath (fileName, 1) + "(" + - String::fromNumber (lineNumber) + ")"); - - return sourceLocation; -} - -} // beast diff --git a/src/beast/modules/beast_core/thread/impl/TrackedMutex.h b/src/beast/modules/beast_core/thread/impl/TrackedMutex.h deleted file mode 100644 index 0946d40c75..0000000000 --- a/src/beast/modules/beast_core/thread/impl/TrackedMutex.h +++ /dev/null @@ -1,173 +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_CORE_THREAD_IMPL_TRACKEDMUTEX_H_INCLUDED -#define BEAST_CORE_THREAD_IMPL_TRACKEDMUTEX_H_INCLUDED - -namespace beast -{ - -/** Common types and member functions for a TrackedMutex */ -class TrackedMutex - : public detail::TrackedMutexBasics::ThreadLockList::Node -{ -public: - class Agent; - class Location; - - //-------------------------------------------------------------------------- - - /** A triplet identifying a mutex, a thread, and source code location. - */ - class Record - { - public: - Record () noexcept; - Record (Record const& other) noexcept; - Record& operator= (Record const& other) noexcept; - - bool isNull () const noexcept; - bool isNotNull () const noexcept; - explicit operator bool() const noexcept; - - /** Returns the name of the mutex. - Since the Mutex may not exist after the Record record is - created, we only provide a String, which is always valid. - */ - String getMutexName () const noexcept; - - /** Returns the name of the associated thread. - The name is generated at the time the record is created, - and might have changed since that time, or may no longer exist. - */ - String getThreadName () const noexcept; - - /** Returns the position within the source code. - This will either be the place a lock was acquired, or the place - where a thread is trying to acquire a lock. The vaue is only - meaningful at the time the Record is created. Since then, the - thread may have changed its state. - */ - String getSourceLocation () const noexcept; - - private: - friend class TrackedMutex; - - Record (String mutexName, String threadName, String sourceLocation); - - String m_mutexName; - String m_threadName; - String m_sourceLocation; - }; - - //-------------------------------------------------------------------------- - - /** Describes a thread that can acquire mutexes. */ - class Agent - { - public: - Agent () noexcept; - Agent (Agent const& other) noexcept; - Agent& operator= (Agent const& other) noexcept; - - bool isNull () const noexcept; - bool isNotNull () const noexcept; - explicit operator bool() const noexcept; - - /** Returns the name of the thread. - The name is generated at the time the Agent record is created, - and might have changed since that time. - */ - String getThreadName () const noexcept; - - /** Returns a Record indicating where the thread is blocked on a mutex. - If the thread is not blocked, a null Record is returned. - The value is only meaningful at the moment of the call as conditions - can change. - */ - Record getBlockedRecord () const noexcept; - - /** Retrieve a list of other locks that this thread holds. - Each lock is represented by a Location indicating the place - The value is only meaningful at the moment of the call as conditions - can change. - @return `true` if the list is not empty. - */ - bool getLockedList (Array & list); - - private: - friend class TrackedMutex; - explicit Agent (detail::TrackedMutexBasics::PerThreadData* thread); - - detail::TrackedMutexBasics::PerThreadData* m_thread; - String m_threadName; - Record m_blocked; - }; - - //-------------------------------------------------------------------------- - - /** Retrieve the name of this mutex. - Thread safety: May be called from any thread. - */ - String getName () const noexcept; - - /** Retrieve a Record for the current owner. - It is only valid at the one instant in time, as the person holding it - might have released it shortly afterwards. If there is no owner, - a null Record is returned. - */ - Record getOwnerRecord () const noexcept; - - /** Retrieve the Agent for the current owner. - It is only valid at the one instant in time, as the person holding it - might have released it shortly afterwards. If there is no owner, - a null Agent is returned. - */ - Agent getOwnerAgent () const noexcept; - - /** Produce a report on the state of all blocked threads. */ - static void generateGlobalBlockedReport (StringArray& report); - -protected: - static String makeThreadName (detail::TrackedMutexBasics::PerThreadData const&) noexcept; - static String makeSourceLocation (char const* fileName, int lineNumber) noexcept; - - TrackedMutex (String const& name) noexcept; - void block (char const* fileName, int lineNumber) const noexcept; - void acquired (char const* fileName, int lineNumber) const noexcept; - void release () const noexcept; - -private: - struct State - { - State (); - Record owner; - detail::TrackedMutexBasics::PerThreadData* thread; - }; - - typedef SharedData SharedState; - - String const m_name; - int mutable m_count; - SharedState mutable m_state; -}; - -} // namespace beast - -#endif diff --git a/src/beast/modules/beast_core/thread/impl/TrackedMutexType.h b/src/beast/modules/beast_core/thread/impl/TrackedMutexType.h deleted file mode 100644 index 5e0528dd25..0000000000 --- a/src/beast/modules/beast_core/thread/impl/TrackedMutexType.h +++ /dev/null @@ -1,100 +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_CORE_THREAD_TRACKEDMUTEXTYPE_H_INCLUDED -#define BEAST_CORE_THREAD_TRACKEDMUTEXTYPE_H_INCLUDED - -namespace beast -{ - -/** A template that gives a Mutex diagnostic tracking capabilities. */ -template -class TrackedMutexType - : public TrackedMutex -{ -public: - /** The type of ScopedLock to use with this TrackedMutexType object. */ - typedef detail::TrackedScopedLock > ScopedLockType; - - /** The type of ScopedTrylock to use with this TrackedMutexType object. */ - typedef detail::TrackedScopedTryLock > ScopedTryLockType; - - /** The type of ScopedUnlock to use with this TrackedMutexType object. */ - typedef detail::TrackedScopedUnlock > ScopedUnlockType; - - /** Construct a mutex, keyed to a particular class. - Just pass 'this' for owner and give it the name of the data member - of your class. - */ - template - TrackedMutexType (Object const* object, - String name, - char const* fileName, - int lineNumber) - : TrackedMutex (detail::TrackedMutexBasics::createName ( - name, fileName, lineNumber)) - { - } - - /** Construct a mutex, without a class association. - These will all get numbered together as a group. - */ - TrackedMutexType (String name, char const* fileName, int lineNumber) - : TrackedMutex (detail::TrackedMutexBasics::createName (name, - fileName, lineNumber)) - { - } - - ~TrackedMutexType () noexcept - { - } - - inline void lock (char const* fileName, int lineNumber) const noexcept - { - block (fileName, lineNumber); - MutexTraits ::lock (m_mutex); - acquired (fileName, lineNumber); - } - - inline void unlock () const noexcept - { - release (); - MutexTraits ::unlock (m_mutex); - } - - // VFALCO NOTE: We could use enable_if here... - inline bool try_lock (char const* fileName, int lineNumber) const noexcept - { - bool const success = MutexTraits ::try_lock (m_mutex); - if (success) - { - // Hack, call block to prevent counts from going wrong. - block (fileName, lineNumber); - acquired (fileName, lineNumber); - } - return success; - } - -private: - Mutex const m_mutex; -}; - -} // namespace beast - -#endif diff --git a/src/beast/modules/beast_core/thread/impl/UntrackedMutexType.h b/src/beast/modules/beast_core/thread/impl/UntrackedMutexType.h deleted file mode 100644 index 22c53d27d5..0000000000 --- a/src/beast/modules/beast_core/thread/impl/UntrackedMutexType.h +++ /dev/null @@ -1,87 +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_CORE_THREAD_IMPL_UNTRACKEDMUTEX_H_INCLUDED -#define BEAST_CORE_THREAD_IMPL_UNTRACKEDMUTEX_H_INCLUDED - -namespace beast -{ - -/** A drop-in replacement for TrackedMutex without the tracking. -*/ -template -class UntrackedMutexType - : public Uncopyable -{ -public: - typedef detail::UntrackedScopedLock > ScopedLockType; - typedef detail::UntrackedScopedTryLock > ScopedTryLockType; - typedef detail::UntrackedScopedUnlock > ScopedUnlockType; - - template - inline UntrackedMutexType (Object const*, String name, char const*, int) noexcept - { - } - - inline UntrackedMutexType (String, char const*, int) noexcept - { - } - - inline UntrackedMutexType () noexcept - { - } - - inline ~UntrackedMutexType () noexcept - { - } - - inline void lock () const noexcept - { - MutexTraits ::lock (m_mutex); - } - - inline void lock (char const*, int) const noexcept - { - MutexTraits ::lock (m_mutex); - } - - inline void unlock () const noexcept - { - MutexTraits ::unlock (m_mutex); - } - - // VFALCO NOTE: We could use enable_if here... - - inline bool try_lock () const noexcept - { - return MutexTraits ::try_lock (m_mutex); - } - - inline bool try_lock (char const*, int) const noexcept - { - return MutexTraits ::try_lock (m_mutex); - } - -private: - Mutex mutable m_mutex; -}; - -} // namespace beast - -#endif diff --git a/src/beast/modules/beast_core/threads/ChildProcess.cpp b/src/beast/modules/beast_core/threads/ChildProcess.cpp deleted file mode 100644 index 46f465e10e..0000000000 --- a/src/beast/modules/beast_core/threads/ChildProcess.cpp +++ /dev/null @@ -1,97 +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 -{ - -ChildProcess::ChildProcess() {} -ChildProcess::~ChildProcess() {} - -bool ChildProcess::waitForProcessToFinish (const int timeoutMs) const -{ - const uint32 timeoutTime = Time::getMillisecondCounter() + (uint32) timeoutMs; - - do - { - if (! isRunning()) - return true; - } - while (timeoutMs < 0 || Time::getMillisecondCounter() < timeoutTime); - - return false; -} - -String ChildProcess::readAllProcessOutput() -{ - MemoryOutputStream result; - - for (;;) - { - char buffer [512]; - const int num = readProcessOutput (buffer, sizeof (buffer)); - - if (num <= 0) - break; - - result.write (buffer, (size_t) num); - } - - return result.toString(); -} - -//============================================================================== - -class ChildProcess_test : public unit_test::suite -{ -public: - void run() - { - #if BEAST_WINDOWS || BEAST_MAC || BEAST_LINUX - ChildProcess p; - - #if BEAST_WINDOWS - expect (p.start ("tasklist")); - #else - expect (p.start ("ls /")); - #endif - - if (! p.waitForProcessToFinish (10 * 1000)) - { - if (p.kill ()) - p.waitForProcessToFinish (-1); - } - - //String output (p.readAllProcessOutput()); - //expect (output.isNotEmpty()); - #endif - } -}; - -// VFALCO NOTE I had to disable this test because it was leaving -// behind a zombie process and making other unit tests fail. -// It doesnt happen with a debugger attached, or if the -// unit test is run individually. -// -BEAST_DEFINE_TESTSUITE_MANUAL(ChildProcess,beast_core,beast); - -} // beast diff --git a/src/beast/modules/beast_core/threads/ChildProcess.h b/src/beast/modules/beast_core/threads/ChildProcess.h deleted file mode 100644 index 1561274606..0000000000 --- a/src/beast/modules/beast_core/threads/ChildProcess.h +++ /dev/null @@ -1,101 +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_CHILDPROCESS_H_INCLUDED -#define BEAST_CHILDPROCESS_H_INCLUDED - -namespace beast -{ - -//============================================================================== -/** - Launches and monitors a child process. - - This class lets you launch an executable, and read its output. You can also - use it to check whether the child process has finished. -*/ -class BEAST_API ChildProcess : LeakChecked , public Uncopyable -{ -public: - //============================================================================== - /** Creates a process object. - To actually launch the process, use start(). - */ - ChildProcess(); - - /** Destructor. - Note that deleting this object won't terminate the child process. - */ - ~ChildProcess(); - - /** Attempts to launch a child process command. - - The command should be the name of the executable file, followed by any arguments - that are required. - If the process has already been launched, this will launch it again. If a problem - occurs, the method will return false. - */ - bool start (const String& command); - - /** Attempts to launch a child process command. - - The first argument should be the name of the executable file, followed by any other - arguments that are needed. - If the process has already been launched, this will launch it again. If a problem - occurs, the method will return false. - */ - bool start (const StringArray& arguments); - - /** Returns true if the child process is alive. */ - bool isRunning() const; - - /** Attempts to read some output from the child process. - This will attempt to read up to the given number of bytes of data from the - process. It returns the number of bytes that were actually read. - */ - int readProcessOutput (void* destBuffer, int numBytesToRead); - - /** Blocks until the process has finished, and then returns its complete output - as a string. - */ - String readAllProcessOutput(); - - /** Blocks until the process is no longer running. */ - bool waitForProcessToFinish (int timeoutMs) const; - - /** Attempts to kill the child process. - Returns true if it succeeded. Trying to read from the process after calling this may - result in undefined behaviour. - */ - bool kill(); - -private: - //============================================================================== - class ActiveProcess; - friend class ScopedPointer; - ScopedPointer activeProcess; -}; - -} // namespace beast - -#endif // BEAST_CHILDPROCESS_H_INCLUDED diff --git a/src/beast/modules/beast_core/threads/CriticalSection.h b/src/beast/modules/beast_core/threads/CriticalSection.h index b51003e0bc..1192764c8f 100644 --- a/src/beast/modules/beast_core/threads/CriticalSection.h +++ b/src/beast/modules/beast_core/threads/CriticalSection.h @@ -24,8 +24,9 @@ #ifndef BEAST_CRITICALSECTION_H_INCLUDED #define BEAST_CRITICALSECTION_H_INCLUDED -namespace beast -{ +#include "ScopedLock.h" + +namespace beast { //============================================================================== /** @@ -35,9 +36,9 @@ namespace beast one of these is by using RAII in the form of a local ScopedLock object - have a look through the codebase for many examples of how to do this. - @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, ReadWriteLock, Thread, InterProcessLock + @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, Thread */ -class BEAST_API CriticalSection : public Uncopyable +class CriticalSection : public Uncopyable { public: //============================================================================== @@ -117,9 +118,9 @@ private: // a block of memory here that's big enough to be used internally as a windows // CRITICAL_SECTION structure. #if BEAST_64BIT - uint8 section[44]; + std::uint8_t section[44]; #else - uint8 section[24]; + std::uint8_t section[24]; #endif #else mutable pthread_mutex_t mutex; @@ -134,9 +135,9 @@ private: This is currently used by some templated classes, and most compilers should manage to optimise it out of existence. - @see CriticalSection, Array, OwnedArray, SharedObjectArray + @see CriticalSection, Array, SharedObjectArray */ -class BEAST_API DummyCriticalSection : public Uncopyable +class DummyCriticalSection : public Uncopyable { public: inline DummyCriticalSection() noexcept {} @@ -255,6 +256,6 @@ typedef CriticalSection::ScopedUnlockType ScopedUnlock; */ typedef CriticalSection::ScopedTryLockType ScopedTryLock; -} // namespace beast +} // beast #endif // BEAST_CRITICALSECTION_H_INCLUDED diff --git a/src/beast/modules/beast_core/threads/DynamicLibrary.h b/src/beast/modules/beast_core/threads/DynamicLibrary.h index e1bec186ae..df8fbc180f 100644 --- a/src/beast/modules/beast_core/threads/DynamicLibrary.h +++ b/src/beast/modules/beast_core/threads/DynamicLibrary.h @@ -34,7 +34,7 @@ namespace beast Since the DLL is freed when this object is deleted, it's handy for managing library lifetimes using RAII. */ -class BEAST_API DynamicLibrary : LeakChecked , public Uncopyable +class DynamicLibrary : LeakChecked , public Uncopyable { public: /** Creates an unopened DynamicLibrary object. @@ -77,6 +77,6 @@ private: void* handle; }; -} // namespace beast +} // beast #endif // BEAST_DYNAMICLIBRARY_H_INCLUDED diff --git a/src/beast/modules/beast_core/threads/HighResolutionTimer.cpp b/src/beast/modules/beast_core/threads/HighResolutionTimer.cpp deleted file mode 100644 index 6298bb8831..0000000000 --- a/src/beast/modules/beast_core/threads/HighResolutionTimer.cpp +++ /dev/null @@ -1,36 +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 -{ - -HighResolutionTimer::HighResolutionTimer() { pimpl = new Pimpl (*this); } -HighResolutionTimer::~HighResolutionTimer() { stopTimer(); } - -void HighResolutionTimer::startTimer (int periodMs) { pimpl->start (bmax (1, periodMs)); } -void HighResolutionTimer::stopTimer() { pimpl->stop(); } - -bool HighResolutionTimer::isTimerRunning() const noexcept { return pimpl->periodMs != 0; } -int HighResolutionTimer::getTimerInterval() const noexcept { return pimpl->periodMs; } - -} // namespace beast diff --git a/src/beast/modules/beast_core/threads/HighResolutionTimer.h b/src/beast/modules/beast_core/threads/HighResolutionTimer.h deleted file mode 100644 index f27ed16270..0000000000 --- a/src/beast/modules/beast_core/threads/HighResolutionTimer.h +++ /dev/null @@ -1,106 +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_HIGHRESOLUTIONTIMER_H_INCLUDED -#define BEAST_HIGHRESOLUTIONTIMER_H_INCLUDED - -namespace beast -{ - -/** - A high-resolution periodic timer. - - This provides accurately-timed regular callbacks. Unlike the normal Timer - class, this one uses a dedicated thread, not the message thread, so is - far more stable and precise. - - You should only use this class in situations where you really need accuracy, - because unlike the normal Timer class, which is very lightweight and cheap - to start/stop, the HighResolutionTimer will use far more resources, and - starting/stopping it may involve launching and killing threads. - - @see Timer -*/ -class BEAST_API HighResolutionTimer : LeakChecked , public Uncopyable -{ -protected: - /** Creates a HighResolutionTimer. - When created, the timer is stopped, so use startTimer() to get it going. - */ - HighResolutionTimer(); - -public: - /** Destructor. */ - virtual ~HighResolutionTimer(); - - //============================================================================== - /** The user-defined callback routine that actually gets called periodically. - - This will be called on a dedicated timer thread, so make sure your - implementation is thread-safe! - - It's perfectly ok to call startTimer() or stopTimer() from within this - callback to change the subsequent intervals. - */ - virtual void hiResTimerCallback() = 0; - - //============================================================================== - /** Starts the timer and sets the length of interval required. - - If the timer is already started, this will reset its counter, so the - time between calling this method and the next timer callback will not be - less than the interval length passed in. - - @param intervalInMilliseconds the interval to use (any values less than 1 will be - rounded up to 1) - */ - void startTimer (int intervalInMilliseconds); - - /** Stops the timer. - - This method may block while it waits for pending callbacks to complete. Once it - returns, no more callbacks will be made. If it is called from the timer's own thread, - it will cancel the timer after the current callback returns. - */ - void stopTimer(); - - /** Checks if the timer has been started. - @returns true if the timer is running. - */ - bool isTimerRunning() const noexcept; - - /** Returns the timer's interval. - @returns the timer's interval in milliseconds if it's running, or 0 if it's not. - */ - int getTimerInterval() const noexcept; - -private: - struct Pimpl; - friend struct Pimpl; - friend class ScopedPointer; - ScopedPointer pimpl; -}; - -} // namespace beast - -#endif // BEAST_HIGHRESOLUTIONTIMER_H_INCLUDED diff --git a/src/beast/modules/beast_core/threads/InterProcessLock.h b/src/beast/modules/beast_core/threads/InterProcessLock.h deleted file mode 100644 index a06c5d5685..0000000000 --- a/src/beast/modules/beast_core/threads/InterProcessLock.h +++ /dev/null @@ -1,122 +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_INTERPROCESSLOCK_H_INCLUDED -#define BEAST_INTERPROCESSLOCK_H_INCLUDED - -namespace beast -{ - -//============================================================================== -/** - Acts as a critical section which processes can use to block each other. - - @see CriticalSection -*/ -class BEAST_API InterProcessLock : public Uncopyable -{ -public: - //============================================================================== - /** Creates a lock object. - @param name a name that processes will use to identify this lock object - */ - explicit InterProcessLock (const String& name); - - /** Destructor. - This will also release the lock if it's currently held by this process. - */ - ~InterProcessLock(); - - //============================================================================== - /** Attempts to lock the critical section. - - @param timeOutMillisecs how many milliseconds to wait if the lock is already - held by another process - a value of 0 will return - immediately, negative values will wait forever - @returns true if the lock could be gained within the timeout period, or - false if the timeout expired. - */ - bool enter (int timeOutMillisecs = -1); - - /** Releases the lock if it's currently held by this process. */ - void exit(); - - //============================================================================== - /** - Automatically locks and unlocks an InterProcessLock object. - - This works like a ScopedLock, but using an InterprocessLock rather than - a CriticalSection. - - @see ScopedLock - */ - class ScopedLockType : public Uncopyable - { - public: - //============================================================================== - /** Creates a scoped lock. - - As soon as it is created, this will lock the InterProcessLock, and - when the ScopedLockType object is deleted, the InterProcessLock will - be unlocked. - - Note that since an InterprocessLock can fail due to errors, you should check - isLocked() to make sure that the lock was successful before using it. - - 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. - */ - explicit ScopedLockType (InterProcessLock& l) : ipLock (l) { lockWasSuccessful = l.enter(); } - - /** Destructor. - - The InterProcessLock 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 ~ScopedLockType() { ipLock.exit(); } - - /** Returns true if the InterProcessLock was successfully locked. */ - bool isLocked() const noexcept { return lockWasSuccessful; } - - private: - //============================================================================== - InterProcessLock& ipLock; - bool lockWasSuccessful; - }; - -private: - //============================================================================== - class Pimpl; - friend class ScopedPointer ; - ScopedPointer pimpl; - - CriticalSection lock; - String name; -}; - -} // namespace beast - -#endif // BEAST_INTERPROCESSLOCK_H_INCLUDED diff --git a/src/beast/modules/beast_core/threads/Process.h b/src/beast/modules/beast_core/threads/Process.h index ef6e242f8c..a9826c7afa 100644 --- a/src/beast/modules/beast_core/threads/Process.h +++ b/src/beast/modules/beast_core/threads/Process.h @@ -24,8 +24,7 @@ #ifndef BEAST_PROCESS_H_INCLUDED #define BEAST_PROCESS_H_INCLUDED -namespace beast -{ +namespace beast { //============================================================================== /** Represents the current executable's process. @@ -35,7 +34,7 @@ namespace beast @see Thread, BEASTApplication */ -class BEAST_API Process : public Uncopyable +class Process : public Uncopyable { public: //============================================================================== @@ -91,18 +90,12 @@ public: static void lowerPrivilege(); /** Returns true if this process is being hosted by a debugger. */ - static bool BEAST_CALLTYPE isRunningUnderDebugger(); + static bool isRunningUnderDebugger(); //============================================================================== /** Tries to launch the OS's default reader application for a given file or URL. */ static bool openDocument (const String& documentURL, const String& parameters); - /** Tries to launch the OS's default email application to let the user create a message. */ - static bool openEmailWithAttachments (const String& targetEmailAddress, - const String& emailSubject, - const String& bodyText, - const StringArray& filesToAttach); - #if BEAST_WINDOWS || DOXYGEN //============================================================================== /** WINDOWS ONLY - This returns the HINSTANCE of the current module. @@ -118,7 +111,7 @@ public: to provide the correct module handle in your DllMain() function, because the system relies on the correct instance handle when opening windows. */ - static void* BEAST_CALLTYPE getCurrentModuleInstanceHandle() noexcept; + static void* getCurrentModuleInstanceHandle() noexcept; /** WINDOWS ONLY - Sets a new module handle to be used by the library. @@ -127,7 +120,7 @@ public: @see getCurrentModuleInstanceHandle() */ - static void BEAST_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) noexcept; + static void setCurrentModuleInstanceHandle (void* newHandle) noexcept; #endif #if BEAST_MAC || DOXYGEN @@ -140,6 +133,6 @@ private: Process(); }; -} // namespace beast +} // beast #endif // BEAST_PROCESS_H_INCLUDED diff --git a/src/beast/modules/beast_core/threads/ScopedLock.h b/src/beast/modules/beast_core/threads/ScopedLock.h index c0b7ec02c5..18d7275a0f 100644 --- a/src/beast/modules/beast_core/threads/ScopedLock.h +++ b/src/beast/modules/beast_core/threads/ScopedLock.h @@ -140,10 +140,10 @@ public: 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 (const LockType& lock) noexcept + inline explicit GenericScopedUnlock (LockType& lock) noexcept : lock_ (lock) { - lock.exit(); + lock.unlock(); } /** Destructor. @@ -155,13 +155,13 @@ public: */ inline ~GenericScopedUnlock() noexcept { - lock_.enter(); + lock_.lock(); } private: //============================================================================== - const LockType& lock_; + LockType& lock_; }; //============================================================================== @@ -243,7 +243,7 @@ private: const bool lockWasSuccessful; }; -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/time/AtExitHook.cpp b/src/beast/modules/beast_core/time/AtExitHook.cpp index b6d5a3fa2d..5ee6e68e15 100644 --- a/src/beast/modules/beast_core/time/AtExitHook.cpp +++ b/src/beast/modules/beast_core/time/AtExitHook.cpp @@ -137,4 +137,4 @@ AtExitHook::~AtExitHook () Manager::get().erase (m_item); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/time/AtExitHook.h b/src/beast/modules/beast_core/time/AtExitHook.h index 703e1733c0..42ddbc55ed 100644 --- a/src/beast/modules/beast_core/time/AtExitHook.h +++ b/src/beast/modules/beast_core/time/AtExitHook.h @@ -20,8 +20,9 @@ #ifndef BEAST_CORE_ATEXITHOOK_H_INCLUDED #define BEAST_CORE_ATEXITHOOK_H_INCLUDED -namespace beast -{ +#include "../../../beast/intrusive/List.h" + +namespace beast { /** Hook for performing activity on program exit. @@ -88,6 +89,6 @@ private: }; /** @} */ -} // namespace beast +} // beast #endif diff --git a/src/beast/modules/beast_core/time/Time.cpp b/src/beast/modules/beast_core/time/Time.cpp index 156670bc08..eea3f1e9b7 100644 --- a/src/beast/modules/beast_core/time/Time.cpp +++ b/src/beast/modules/beast_core/time/Time.cpp @@ -26,18 +26,18 @@ namespace beast namespace TimeHelpers { - static struct tm millisToLocal (const int64 millis) noexcept + static struct tm millisToLocal (const std::int64_t millis) noexcept { struct tm result; - const int64 seconds = millis / 1000; + const std::int64_t seconds = millis / 1000; - if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800)) + if (seconds < 86400LL || seconds >= 2145916800LL) { // use extended maths for dates beyond 1970 to 2037.. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000); - const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200); + const std::int64_t jdm = seconds + timeZoneAdjustment + 210866803200LL; - const int days = (int) (jdm / literal64bit (86400)); + const int days = (int) (jdm / 86400LL); const int a = 32044 + days; const int b = (4 * a + 3) / 146097; const int c = a - (b * 146097) / 4; @@ -51,7 +51,7 @@ namespace TimeHelpers result.tm_wday = (days + 1) % 7; result.tm_yday = -1; - int t = (int) (jdm % literal64bit (86400)); + int t = (int) (jdm % 86400LL); result.tm_hour = t / 3600; t %= 3600; result.tm_min = t / 60; @@ -80,7 +80,7 @@ namespace TimeHelpers return result; } - static int extendedModulo (const int64 value, const int modulo) noexcept + static int extendedModulo (const std::int64_t value, const int modulo) noexcept { return (int) (value >= 0 ? (value % modulo) : (value - ((value / modulo) + 1) * modulo)); @@ -114,7 +114,7 @@ namespace TimeHelpers } } - static uint32 lastMSCounterValue = 0; + static std::uint32_t lastMSCounterValue = 0; } //============================================================================== @@ -128,7 +128,7 @@ Time::Time (const Time& other) noexcept { } -Time::Time (const int64 ms) noexcept +Time::Time (const std::int64_t ms) noexcept : millisSinceEpoch (ms) { } @@ -155,7 +155,7 @@ Time::Time (const int year, + (y * 365) + (y / 4) - (y / 100) + (y / 400) - 32045; - const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200); + const std::int64_t s = ((std::int64_t) jd) * 86400LL - 210866803200LL; millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment)) + milliseconds; @@ -171,7 +171,7 @@ Time::Time (const int year, t.tm_sec = seconds; t.tm_isdst = -1; - millisSinceEpoch = 1000 * (int64) mktime (&t); + millisSinceEpoch = 1000 * (std::int64_t) mktime (&t); if (millisSinceEpoch < 0) millisSinceEpoch = 0; @@ -191,7 +191,7 @@ Time& Time::operator= (const Time& other) noexcept } //============================================================================== -int64 Time::currentTimeMillis() noexcept +std::int64_t Time::currentTimeMillis() noexcept { #if BEAST_WINDOWS struct _timeb t; @@ -200,25 +200,25 @@ int64 Time::currentTimeMillis() noexcept #else _ftime (&t); #endif - return ((int64) t.time) * 1000 + t.millitm; + return ((std::int64_t) t.time) * 1000 + t.millitm; #else struct timeval tv; gettimeofday (&tv, nullptr); - return ((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000; + return ((std::int64_t) tv.tv_sec) * 1000 + tv.tv_usec / 1000; #endif } -Time BEAST_CALLTYPE Time::getCurrentTime() noexcept +Time Time::getCurrentTime() noexcept { return Time (currentTimeMillis()); } //============================================================================== -uint32 beast_millisecondsSinceStartup() noexcept; +std::uint32_t beast_millisecondsSinceStartup() noexcept; -uint32 Time::getMillisecondCounter() noexcept +std::uint32_t Time::getMillisecondCounter() noexcept { - const uint32 now = beast_millisecondsSinceStartup(); + const std::uint32_t now = beast_millisecondsSinceStartup(); if (now < TimeHelpers::lastMSCounterValue) { @@ -236,7 +236,7 @@ uint32 Time::getMillisecondCounter() noexcept return now; } -uint32 Time::getApproximateMillisecondCounter() noexcept +std::uint32_t Time::getApproximateMillisecondCounter() noexcept { if (TimeHelpers::lastMSCounterValue == 0) getMillisecondCounter(); @@ -244,11 +244,11 @@ uint32 Time::getApproximateMillisecondCounter() noexcept return TimeHelpers::lastMSCounterValue; } -void Time::waitForMillisecondCounter (const uint32 targetTime) noexcept +void Time::waitForMillisecondCounter (const std::uint32_t targetTime) noexcept { for (;;) { - const uint32 now = getMillisecondCounter(); + const std::uint32_t now = getMillisecondCounter(); if (now >= targetTime) break; @@ -270,14 +270,14 @@ void Time::waitForMillisecondCounter (const uint32 targetTime) noexcept } //============================================================================== -double Time::highResolutionTicksToSeconds (const int64 ticks) noexcept +double Time::highResolutionTicksToSeconds (const std::int64_t ticks) noexcept { return ticks / (double) getHighResolutionTicksPerSecond(); } -int64 Time::secondsToHighResolutionTicks (const double seconds) noexcept +std::int64_t Time::secondsToHighResolutionTicks (const double seconds) noexcept { - return (int64) (seconds * (double) getHighResolutionTicksPerSecond()); + return (std::int64_t) (seconds * (double) getHighResolutionTicksPerSecond()); } //============================================================================== @@ -443,4 +443,4 @@ bool operator> (Time time1, Time time2) { return time1.toMilliseconds() > bool operator<= (Time time1, Time time2) { return time1.toMilliseconds() <= time2.toMilliseconds(); } bool operator>= (Time time1, Time time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); } -} // namespace beast +} // beast diff --git a/src/beast/modules/beast_core/time/Time.h b/src/beast/modules/beast_core/time/Time.h index dd41e5cbe2..d3c12b328b 100644 --- a/src/beast/modules/beast_core/time/Time.h +++ b/src/beast/modules/beast_core/time/Time.h @@ -36,7 +36,7 @@ namespace beast { @see RelativeTime */ -class BEAST_API Time +class Time { public: //============================================================================== @@ -60,7 +60,7 @@ public: 'epoch' (midnight Jan 1st 1970). @see getCurrentTime, currentTimeMillis */ - explicit Time (int64 millisecondsSinceEpoch) noexcept; + explicit Time (std::int64_t millisecondsSinceEpoch) noexcept; /** Creates a time from a set of date components. @@ -99,7 +99,7 @@ public: @see currentTimeMillis */ - static Time BEAST_CALLTYPE getCurrentTime() noexcept; + static Time getCurrentTime() noexcept; /** Returns `true` if this object represents "no time", or NULL. Internally we check for milliseconds since Epoch equal to zero. @@ -122,7 +122,7 @@ public: midnight jan 1st 1970. @see getMilliseconds */ - int64 toMilliseconds() const noexcept { return millisSinceEpoch; } + std::int64_t toMilliseconds() const noexcept { return millisSinceEpoch; } /** Returns the year. @@ -307,7 +307,7 @@ public: Should be accurate to within a few millisecs, depending on platform, hardware, etc. */ - static int64 currentTimeMillis() noexcept; + static std::int64_t currentTimeMillis() noexcept; /** Returns the number of millisecs since a fixed event (usually system startup). @@ -321,7 +321,7 @@ public: @see getApproximateMillisecondCounter */ - static uint32 getMillisecondCounter() noexcept; + static std::uint32_t getMillisecondCounter() noexcept; /** Returns the number of millisecs since a fixed event (usually system startup). @@ -336,7 +336,7 @@ public: This will make the thread sleep as efficiently as it can while it's waiting. */ - static void waitForMillisecondCounter (uint32 targetTime) noexcept; + static void waitForMillisecondCounter (std::uint32_t targetTime) noexcept; /** Less-accurate but faster version of getMillisecondCounter(). @@ -347,7 +347,7 @@ public: @see getMillisecondCounter */ - static uint32 getApproximateMillisecondCounter() noexcept; + static std::uint32_t getApproximateMillisecondCounter() noexcept; //============================================================================== // High-resolution timers.. @@ -360,59 +360,59 @@ public: @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds, secondsToHighResolutionTicks */ - static int64 getHighResolutionTicks() noexcept; + static std::int64_t getHighResolutionTicks() noexcept; /** Returns the resolution of the high-resolution counter in ticks per second. @see getHighResolutionTicks, highResolutionTicksToSeconds, secondsToHighResolutionTicks */ - static int64 getHighResolutionTicksPerSecond() noexcept; + static std::int64_t getHighResolutionTicksPerSecond() noexcept; /** Converts a number of high-resolution ticks into seconds. @see getHighResolutionTicks, getHighResolutionTicksPerSecond, secondsToHighResolutionTicks */ - static double highResolutionTicksToSeconds (int64 ticks) noexcept; + static double highResolutionTicksToSeconds (std::int64_t ticks) noexcept; /** Converts a number seconds into high-resolution ticks. @see getHighResolutionTicks, getHighResolutionTicksPerSecond, highResolutionTicksToSeconds */ - static int64 secondsToHighResolutionTicks (double seconds) noexcept; + static std::int64_t secondsToHighResolutionTicks (double seconds) noexcept; private: //============================================================================== - int64 millisSinceEpoch; + std::int64_t millisSinceEpoch; }; //============================================================================== /** Adds a RelativeTime to a Time. */ -BEAST_API Time operator+ (Time time, RelativeTime delta); +Time operator+ (Time time, RelativeTime delta); /** Adds a RelativeTime to a Time. */ -BEAST_API Time operator+ (RelativeTime delta, Time time); +Time operator+ (RelativeTime delta, Time time); /** Subtracts a RelativeTime from a Time. */ -BEAST_API Time operator- (Time time, RelativeTime delta); +Time operator- (Time time, RelativeTime delta); /** Returns the relative time difference between two times. */ -BEAST_API const RelativeTime operator- (Time time1, Time time2); +const RelativeTime operator- (Time time1, Time time2); /** Compares two Time objects. */ -BEAST_API bool operator== (Time time1, Time time2); +bool operator== (Time time1, Time time2); /** Compares two Time objects. */ -BEAST_API bool operator!= (Time time1, Time time2); +bool operator!= (Time time1, Time time2); /** Compares two Time objects. */ -BEAST_API bool operator< (Time time1, Time time2); +bool operator< (Time time1, Time time2); /** Compares two Time objects. */ -BEAST_API bool operator<= (Time time1, Time time2); +bool operator<= (Time time1, Time time2); /** Compares two Time objects. */ -BEAST_API bool operator> (Time time1, Time time2); +bool operator> (Time time1, Time time2); /** Compares two Time objects. */ -BEAST_API bool operator>= (Time time1, Time time2); +bool operator>= (Time time1, Time time2); -} // namespace beast +} // beast #endif // BEAST_TIME_H_INCLUDED diff --git a/src/beast/modules/beast_core/xml/XmlDocument.cpp b/src/beast/modules/beast_core/xml/XmlDocument.cpp deleted file mode 100644 index f6d79440c9..0000000000 --- a/src/beast/modules/beast_core/xml/XmlDocument.cpp +++ /dev/null @@ -1,876 +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 -{ - -XmlDocument::XmlDocument (const String& documentText) - : originalText (documentText), - input (nullptr), - outOfData (false), - errorOccurred (false), - needToLoadDTD (false), - ignoreEmptyTextElements (true) -{ -} - -XmlDocument::XmlDocument (const File& file) - : input (nullptr), - outOfData (false), - errorOccurred (false), - needToLoadDTD (false), - ignoreEmptyTextElements (true), - inputSource (new FileInputSource (file)) -{ -} - -XmlDocument::~XmlDocument() -{ -} - -XmlElement* XmlDocument::parse (const File& file) -{ - XmlDocument doc (file); - return doc.getDocumentElement(); -} - -XmlElement* XmlDocument::parse (const String& xmlData) -{ - XmlDocument doc (xmlData); - return doc.getDocumentElement(); -} - -void XmlDocument::setInputSource (InputSource* const newSource) noexcept -{ - inputSource = newSource; -} - -void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) noexcept -{ - ignoreEmptyTextElements = shouldBeIgnored; -} - -namespace XmlIdentifierChars -{ - static bool isIdentifierCharSlow (const beast_wchar c) noexcept - { - return CharacterFunctions::isLetterOrDigit (c) - || c == '_' || c == '-' || c == ':' || c == '.'; - } - - static bool isIdentifierChar (const beast_wchar c) noexcept - { - static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 }; - - return ((int) c < (int) numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0) - : isIdentifierCharSlow (c); - } - - /* - static void generateIdentifierCharConstants() - { - uint32 n[8] = { 0 }; - for (int i = 0; i < 256; ++i) - if (isIdentifierCharSlow (i)) - n[i >> 5] |= (1 << (i & 31)); - - String s; - for (int i = 0; i < 8; ++i) - s << "0x" << String::toHexString ((int) n[i]) << ", "; - - DBG (s); - } - */ - - static String::CharPointerType findEndOfToken (String::CharPointerType p) - { - while (isIdentifierChar (*p)) - ++p; - - return p; - } -} - -XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement) -{ - if (originalText.isEmpty() && inputSource != nullptr) - { - ScopedPointer in (inputSource->createInputStream()); - - if (in != nullptr) - { - MemoryOutputStream data; - data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1); - - #if BEAST_STRING_UTF_TYPE == 8 - if (data.getDataSize() > 2) - { - data.writeByte (0); - const char* text = static_cast (data.getData()); - - if (CharPointer_UTF16::isByteOrderMarkBigEndian (text) - || CharPointer_UTF16::isByteOrderMarkLittleEndian (text)) - { - originalText = data.toString(); - } - else - { - if (CharPointer_UTF8::isByteOrderMark (text)) - text += 3; - - // parse the input buffer directly to avoid copying it all to a string.. - return parseDocumentElement (String::CharPointerType (text), onlyReadOuterDocumentElement); - } - } - #else - originalText = data.toString(); - #endif - } - } - - return parseDocumentElement (originalText.getCharPointer(), onlyReadOuterDocumentElement); -} - -const String& XmlDocument::getLastParseError() const noexcept -{ - return lastError; -} - -void XmlDocument::setLastError (const String& desc, const bool carryOn) -{ - lastError = desc; - errorOccurred = ! carryOn; -} - -String XmlDocument::getFileContents (const String& filename) const -{ - if (inputSource != nullptr) - { - const ScopedPointer in (inputSource->createInputStreamFor (filename.trim().unquoted())); - - if (in != nullptr) - return in->readEntireStreamAsString(); - } - - return String::empty; -} - -beast_wchar XmlDocument::readNextChar() noexcept -{ - const beast_wchar c = input.getAndAdvance(); - - if (c == 0) - { - outOfData = true; - --input; - } - - return c; -} - -XmlElement* XmlDocument::parseDocumentElement (String::CharPointerType textToParse, - const bool onlyReadOuterDocumentElement) -{ - input = textToParse; - errorOccurred = false; - outOfData = false; - needToLoadDTD = true; - - if (textToParse.isEmpty()) - { - lastError = "not enough input"; - } - else if (! parseHeader()) - { - lastError = "malformed header"; - } - else if (! parseDTD()) - { - lastError = "malformed DTD"; - } - else - { - lastError = String::empty; - - ScopedPointer result (readNextElement (! onlyReadOuterDocumentElement)); - - if (! errorOccurred) - return result.release(); - } - - return nullptr; -} - -bool XmlDocument::parseHeader() -{ - skipNextWhiteSpace(); - - if (CharacterFunctions::compareUpTo (input, CharPointer_ASCII (""))); - - if (headerEnd.isEmpty()) - return false; - - #if BEAST_DEBUG - const String encoding (String (input, headerEnd) - .fromFirstOccurrenceOf ("encoding", false, true) - .fromFirstOccurrenceOf ("=", false, false) - .fromFirstOccurrenceOf ("\"", false, false) - .upToFirstOccurrenceOf ("\"", false, false).trim()); - - /* If you load an XML document with a non-UTF encoding type, it may have been - loaded wrongly.. Since all the files are read via the normal beast file streams, - they're treated as UTF-8, so by the time it gets to the parser, the encoding will - have been lost. Best plan is to stick to utf-8 or if you have specific files to - read, use your own code to convert them to a unicode String, and pass that to the - XML parser. - */ - bassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-")); - #endif - - input = headerEnd + 2; - skipNextWhiteSpace(); - } - - return true; -} - -bool XmlDocument::parseDTD() -{ - if (CharacterFunctions::compareUpTo (input, CharPointer_ASCII (" 0;) - { - const beast_wchar c = readNextChar(); - - if (outOfData) - return false; - - if (c == '<') - ++n; - else if (c == '>') - --n; - } - - dtdText = String (dtdStart, input - 1).trim(); - } - - return true; -} - -void XmlDocument::skipNextWhiteSpace() -{ - for (;;) - { - input = input.findEndOfWhitespace(); - - if (input.isEmpty()) - { - outOfData = true; - break; - } - - if (*input == '<') - { - if (input[1] == '!' - && input[2] == '-' - && input[3] == '-') - { - input += 4; - const int closeComment = input.indexOf (CharPointer_ASCII ("-->")); - - if (closeComment < 0) - { - outOfData = true; - break; - } - - input += closeComment + 3; - continue; - } - - if (input[1] == '?') - { - input += 2; - const int closeBracket = input.indexOf (CharPointer_ASCII ("?>")); - - if (closeBracket < 0) - { - outOfData = true; - break; - } - - input += closeBracket + 2; - continue; - } - } - - break; - } -} - -void XmlDocument::readQuotedString (String& result) -{ - const beast_wchar quote = readNextChar(); - - while (! outOfData) - { - const beast_wchar c = readNextChar(); - - if (c == quote) - break; - - --input; - - if (c == '&') - { - readEntity (result); - } - else - { - const String::CharPointerType start (input); - - for (;;) - { - const beast_wchar character = *input; - - if (character == quote) - { - result.appendCharPointer (start, input); - ++input; - return; - } - else if (character == '&') - { - result.appendCharPointer (start, input); - break; - } - else if (character == 0) - { - outOfData = true; - setLastError ("unmatched quotes", false); - break; - } - - ++input; - } - } - } -} - -XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) -{ - XmlElement* node = nullptr; - - skipNextWhiteSpace(); - if (outOfData) - return nullptr; - - if (*input == '<') - { - ++input; - String::CharPointerType endOfToken (XmlIdentifierChars::findEndOfToken (input)); - - if (endOfToken == input) - { - // no tag name - but allow for a gap after the '<' before giving an error - skipNextWhiteSpace(); - endOfToken = XmlIdentifierChars::findEndOfToken (input); - - if (endOfToken == input) - { - setLastError ("tag name missing", false); - return node; - } - } - - node = new XmlElement (String (input, endOfToken)); - input = endOfToken; - LinkedListPointer::Appender attributeAppender (node->attributes); - - // look for attributes - for (;;) - { - skipNextWhiteSpace(); - - const beast_wchar c = *input; - - // empty tag.. - if (c == '/' && input[1] == '>') - { - input += 2; - break; - } - - // parse the guts of the element.. - if (c == '>') - { - ++input; - - if (alsoParseSubElements) - readChildElements (node); - - break; - } - - // get an attribute.. - if (XmlIdentifierChars::isIdentifierChar (c)) - { - String::CharPointerType attNameEnd (XmlIdentifierChars::findEndOfToken (input)); - - if (attNameEnd != input) - { - const String::CharPointerType attNameStart (input); - input = attNameEnd; - - skipNextWhiteSpace(); - - if (readNextChar() == '=') - { - skipNextWhiteSpace(); - - const beast_wchar nextChar = *input; - - if (nextChar == '"' || nextChar == '\'') - { - XmlElement::XmlAttributeNode* const newAtt - = new XmlElement::XmlAttributeNode (String (attNameStart, attNameEnd), - String::empty); - - readQuotedString (newAtt->value); - attributeAppender.append (newAtt); - continue; - } - } - else - { - setLastError ("expected '=' after attribute '" - + String (attNameStart, attNameEnd) + "'", false); - return node; - } - } - } - else - { - if (! outOfData) - setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false); - } - - break; - } - } - - return node; -} - -void XmlDocument::readChildElements (XmlElement* parent) -{ - LinkedListPointer::Appender childAppender (parent->firstChildElement); - - for (;;) - { - const String::CharPointerType preWhitespaceInput (input); - skipNextWhiteSpace(); - - if (outOfData) - { - setLastError ("unmatched tags", false); - break; - } - - if (*input == '<') - { - const beast_wchar c1 = input[1]; - - if (c1 == '/') - { - // our close tag.. - const int closeTag = input.indexOf ((beast_wchar) '>'); - - if (closeTag >= 0) - input += closeTag + 1; - - break; - } - - if (c1 == '!' && CharacterFunctions::compareUpTo (input + 2, CharPointer_ASCII ("[CDATA["), 7) == 0) - { - input += 9; - const String::CharPointerType inputStart (input); - - for (;;) - { - const beast_wchar c0 = *input; - - if (c0 == 0) - { - setLastError ("unterminated CDATA section", false); - outOfData = true; - break; - } - else if (c0 == ']' - && input[1] == ']' - && input[2] == '>') - { - childAppender.append (XmlElement::createTextElement (String (inputStart, input))); - input += 3; - break; - } - - ++input; - } - } - else - { - // this is some other element, so parse and add it.. - if (XmlElement* const n = readNextElement (true)) - childAppender.append (n); - else - break; - } - } - else // must be a character block - { - input = preWhitespaceInput; // roll back to include the leading whitespace - String textElementContent; - - for (;;) - { - const beast_wchar c = *input; - - if (c == '<') - break; - - if (c == 0) - { - setLastError ("unmatched tags", false); - outOfData = true; - return; - } - - if (c == '&') - { - String entity; - readEntity (entity); - - if (entity.startsWithChar ('<') && entity [1] != 0) - { - const String::CharPointerType oldInput (input); - const bool oldOutOfData = outOfData; - - input = entity.getCharPointer(); - outOfData = false; - - for (;;) - { - XmlElement* const n = readNextElement (true); - - if (n == nullptr) - break; - - childAppender.append (n); - } - - input = oldInput; - outOfData = oldOutOfData; - } - else - { - textElementContent += entity; - } - } - else - { - const String::CharPointerType start (input); - - for (;;) - { - const beast_wchar nextChar = *input; - - if (nextChar == '<' || nextChar == '&') - break; - - if (nextChar == 0) - { - setLastError ("unmatched tags", false); - outOfData = true; - return; - } - - ++input; - } - - textElementContent.appendCharPointer (start, input); - } - } - - if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars()) - childAppender.append (XmlElement::createTextElement (textElementContent)); - } - } -} - -void XmlDocument::readEntity (String& result) -{ - // skip over the ampersand - ++input; - - if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("amp;"), 4) == 0) - { - input += 4; - result += '&'; - } - else if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("quot;"), 5) == 0) - { - input += 5; - result += '"'; - } - else if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("apos;"), 5) == 0) - { - input += 5; - result += '\''; - } - else if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("lt;"), 3) == 0) - { - input += 3; - result += '<'; - } - else if (input.compareIgnoreCaseUpTo (CharPointer_ASCII ("gt;"), 3) == 0) - { - input += 3; - result += '>'; - } - else if (*input == '#') - { - int charCode = 0; - ++input; - - if (*input == 'x' || *input == 'X') - { - ++input; - int numChars = 0; - - while (input[0] != ';') - { - const int hexValue = CharacterFunctions::getHexDigitValue (input[0]); - - if (hexValue < 0 || ++numChars > 8) - { - setLastError ("illegal escape sequence", true); - break; - } - - charCode = (charCode << 4) | hexValue; - ++input; - } - - ++input; - } - else if (input[0] >= '0' && input[0] <= '9') - { - int numChars = 0; - - while (input[0] != ';') - { - if (++numChars > 12) - { - setLastError ("illegal escape sequence", true); - break; - } - - charCode = charCode * 10 + ((int) input[0] - '0'); - ++input; - } - - ++input; - } - else - { - setLastError ("illegal escape sequence", true); - result += '&'; - return; - } - - result << (beast_wchar) charCode; - } - else - { - const String::CharPointerType entityNameStart (input); - const int closingSemiColon = input.indexOf ((beast_wchar) ';'); - - if (closingSemiColon < 0) - { - outOfData = true; - result += '&'; - } - else - { - input += closingSemiColon + 1; - - result += expandExternalEntity (String (entityNameStart, (size_t) closingSemiColon)); - } - } -} - -String XmlDocument::expandEntity (const String& ent) -{ - if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&'); - if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"'); - if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\''); - if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<'); - if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>'); - - if (ent[0] == '#') - { - const beast_wchar char1 = ent[1]; - - if (char1 == 'x' || char1 == 'X') - return String::charToString (static_cast (ent.substring (2).getHexValue32())); - - if (char1 >= '0' && char1 <= '9') - return String::charToString (static_cast (ent.substring (1).getIntValue())); - - setLastError ("illegal escape sequence", false); - return String::charToString ('&'); - } - - return expandExternalEntity (ent); -} - -String XmlDocument::expandExternalEntity (const String& entity) -{ - if (needToLoadDTD) - { - if (dtdText.isNotEmpty()) - { - dtdText = dtdText.trimCharactersAtEnd (">"); - tokenisedDTD.addTokens (dtdText, true); - - if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system") - && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString()) - { - const String fn (tokenisedDTD [tokenisedDTD.size() - 1]); - - tokenisedDTD.clear(); - tokenisedDTD.addTokens (getFileContents (fn), true); - } - else - { - tokenisedDTD.clear(); - const int openBracket = dtdText.indexOfChar ('['); - - if (openBracket > 0) - { - const int closeBracket = dtdText.lastIndexOfChar (']'); - - if (closeBracket > openBracket) - tokenisedDTD.addTokens (dtdText.substring (openBracket + 1, - closeBracket), true); - } - } - - for (int i = tokenisedDTD.size(); --i >= 0;) - { - if (tokenisedDTD[i].startsWithChar ('%') - && tokenisedDTD[i].endsWithChar (';')) - { - const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1))); - StringArray newToks; - newToks.addTokens (parsed, true); - - tokenisedDTD.remove (i); - - for (int j = newToks.size(); --j >= 0;) - tokenisedDTD.insert (i, newToks[j]); - } - } - } - - needToLoadDTD = false; - } - - for (int i = 0; i < tokenisedDTD.size(); ++i) - { - if (tokenisedDTD[i] == entity) - { - if (tokenisedDTD[i - 1].equalsIgnoreCase ("").trim().unquoted()); - - // check for sub-entities.. - int ampersand = ent.indexOfChar ('&'); - - while (ampersand >= 0) - { - const int semiColon = ent.indexOf (i + 1, ";"); - - if (semiColon < 0) - { - setLastError ("entity without terminating semi-colon", false); - break; - } - - const String resolved (expandEntity (ent.substring (i + 1, semiColon))); - - ent = ent.substring (0, ampersand) - + resolved - + ent.substring (semiColon + 1); - - ampersand = ent.indexOfChar (semiColon + 1, '&'); - } - - return ent; - } - } - } - - setLastError ("unknown entity", true); - - return entity; -} - -String XmlDocument::getParameterEntity (const String& entity) -{ - for (int i = 0; i < tokenisedDTD.size(); ++i) - { - if (tokenisedDTD[i] == entity - && tokenisedDTD [i - 1] == "%" - && tokenisedDTD [i - 2].equalsIgnoreCase ("")); - - if (ent.equalsIgnoreCase ("system")) - return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">")); - - return ent.trim().unquoted(); - } - } - - return entity; -} - -} // namespace beast diff --git a/src/beast/modules/beast_core/xml/XmlDocument.h b/src/beast/modules/beast_core/xml/XmlDocument.h deleted file mode 100644 index ade90ecff7..0000000000 --- a/src/beast/modules/beast_core/xml/XmlDocument.h +++ /dev/null @@ -1,179 +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_XMLDOCUMENT_H_INCLUDED -#define BEAST_XMLDOCUMENT_H_INCLUDED - -namespace beast -{ - -class XmlElement; - -//============================================================================== -/** - Parses a text-based XML document and creates an XmlElement object from it. - - The parser will parse DTDs to load external entities but won't - check the document for validity against the DTD. - - e.g. - @code - - XmlDocument myDocument (File ("myfile.xml")); - XmlElement* mainElement = myDocument.getDocumentElement(); - - if (mainElement == nullptr) - { - String error = myDocument.getLastParseError(); - } - else - { - ..use the element - } - - @endcode - - Or you can use the static helper methods for quick parsing.. - - @code - XmlElement* xml = XmlDocument::parse (myXmlFile); - - if (xml != nullptr && xml->hasTagName ("foobar")) - { - ...etc - @endcode - - @see XmlElement -*/ -class BEAST_API XmlDocument : LeakChecked , public Uncopyable -{ -public: - //============================================================================== - /** Creates an XmlDocument from the xml text. - The text doesn't actually get parsed until the getDocumentElement() method is called. - */ - XmlDocument (const String& documentText); - - /** Creates an XmlDocument from a file. - The text doesn't actually get parsed until the getDocumentElement() method is called. - */ - XmlDocument (const File& file); - - /** Destructor. */ - ~XmlDocument(); - - //============================================================================== - /** Creates an XmlElement object to represent the main document node. - - This method will do the actual parsing of the text, and if there's a - parse error, it may returns nullptr (and you can find out the error using - the getLastParseError() method). - - See also the parse() methods, which provide a shorthand way to quickly - parse a file or string. - - @param onlyReadOuterDocumentElement if true, the parser will only read the - first section of the file, and will only - return the outer document element - this - allows quick checking of large files to - see if they contain the correct type of - tag, without having to parse the entire file - @returns a new XmlElement which the caller will need to delete, or null if - there was an error. - @see getLastParseError - */ - XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false); - - /** Returns the parsing error that occurred the last time getDocumentElement was called. - - @returns the error, or an empty string if there was no error. - */ - const String& getLastParseError() const noexcept; - - /** Sets an input source object to use for parsing documents that reference external entities. - - If the document has been created from a file, this probably won't be needed, but - if you're parsing some text and there might be a DTD that references external - files, you may need to create a custom input source that can retrieve the - other files it needs. - - The object that is passed-in will be deleted automatically when no longer needed. - - @see InputSource - */ - void setInputSource (InputSource* newSource) noexcept; - - /** Sets a flag to change the treatment of empty text elements. - - If this is true (the default state), then any text elements that contain only - whitespace characters will be ingored during parsing. If you need to catch - whitespace-only text, then you should set this to false before calling the - getDocumentElement() method. - */ - void setEmptyTextElementsIgnored (bool shouldBeIgnored) noexcept; - - //============================================================================== - /** A handy static method that parses a file. - This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it. - @returns a new XmlElement which the caller will need to delete, or null if there was an error. - */ - static XmlElement* parse (const File& file); - - /** A handy static method that parses some XML data. - This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it. - @returns a new XmlElement which the caller will need to delete, or null if there was an error. - */ - static XmlElement* parse (const String& xmlData); - - - //============================================================================== -private: - XmlElement* parseDocumentElement (String::CharPointerType, bool outer); - void setLastError (const String& desc, bool carryOn); - bool parseHeader(); - bool parseDTD(); - void skipNextWhiteSpace(); - beast_wchar readNextChar() noexcept; - XmlElement* readNextElement (bool alsoParseSubElements); - void readChildElements (XmlElement* parent); - void readQuotedString (String& result); - void readEntity (String& result); - - String getFileContents (const String& filename) const; - String expandEntity (const String& entity); - String expandExternalEntity (const String& entity); - String getParameterEntity (const String& entity); - - String originalText; - String::CharPointerType input; - bool outOfData, errorOccurred; - - String lastError, dtdText; - StringArray tokenisedDTD; - bool needToLoadDTD, ignoreEmptyTextElements; - ScopedPointer inputSource; -}; - -} // namespace beast - -#endif diff --git a/src/beast/modules/beast_core/xml/XmlElement.cpp b/src/beast/modules/beast_core/xml/XmlElement.cpp deleted file mode 100644 index 5aab136679..0000000000 --- a/src/beast/modules/beast_core/xml/XmlElement.cpp +++ /dev/null @@ -1,826 +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 -{ - -XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) noexcept - : name (other.name), - value (other.value) -{ -} - -XmlElement::XmlAttributeNode::XmlAttributeNode (const String& n, const String& v) noexcept - : name (n), value (v) -{ - #if BEAST_DEBUG - // this checks whether the attribute name string contains any illegal characters.. - for (String::CharPointerType t (name.getCharPointer()); ! t.isEmpty(); ++t) - bassert (t.isLetterOrDigit() || *t == '_' || *t == '-' || *t == ':'); - #endif -} - -inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const noexcept -{ - return name.equalsIgnoreCase (nameToMatch); -} - -//============================================================================== -XmlElement::XmlElement (const String& tag) noexcept - : tagName (tag) -{ - // the tag name mustn't be empty, or it'll look like a text element! - bassert (tag.containsNonWhitespaceChars()); - - // The tag can't contain spaces or other characters that would create invalid XML! - bassert (! tag.containsAnyOf (" <>/&")); -} - -XmlElement::XmlElement (int /*dummy*/) noexcept -{ -} - -XmlElement::XmlElement (const XmlElement& other) - : tagName (other.tagName) -{ - copyChildrenAndAttributesFrom (other); -} - -XmlElement& XmlElement::operator= (const XmlElement& other) -{ - if (this != &other) - { - removeAllAttributes(); - deleteAllChildElements(); - - tagName = other.tagName; - - copyChildrenAndAttributesFrom (other); - } - - return *this; -} - -#if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS -XmlElement::XmlElement (XmlElement&& other) noexcept - : nextListItem (static_cast &&> (other.nextListItem)), - firstChildElement (static_cast &&> (other.firstChildElement)), - attributes (static_cast &&> (other.attributes)), - tagName (static_cast (other.tagName)) -{ -} - -XmlElement& XmlElement::operator= (XmlElement&& other) noexcept -{ - bassert (this != &other); // hopefully the compiler should make this situation impossible! - - removeAllAttributes(); - deleteAllChildElements(); - - nextListItem = static_cast &&> (other.nextListItem); - firstChildElement = static_cast &&> (other.firstChildElement); - attributes = static_cast &&> (other.attributes); - tagName = static_cast (other.tagName); - - return *this; -} -#endif - -void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) -{ - bassert (firstChildElement.get() == nullptr); - firstChildElement.addCopyOfList (other.firstChildElement); - - bassert (attributes.get() == nullptr); - attributes.addCopyOfList (other.attributes); -} - -XmlElement::~XmlElement() noexcept -{ - firstChildElement.deleteAll(); - attributes.deleteAll(); -} - -//============================================================================== -namespace XmlOutputFunctions -{ - #if 0 // (These functions are just used to generate the lookup table used below) - bool isLegalXmlCharSlow (const beast_wchar character) noexcept - { - if ((character >= 'a' && character <= 'z') - || (character >= 'A' && character <= 'Z') - || (character >= '0' && character <= '9')) - return true; - - const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|"; - - do - { - if (((beast_wchar) (uint8) *t) == character) - return true; - } - while (*++t != 0); - - return false; - } - - void generateLegalCharLookupTable() - { - uint8 n[32] = { 0 }; - for (int i = 0; i < 256; ++i) - if (isLegalXmlCharSlow (i)) - n[i >> 3] |= (1 << (i & 7)); - - String s; - for (int i = 0; i < 32; ++i) - s << (int) n[i] << ", "; - - DBG (s); - } - #endif - - static bool isLegalXmlChar (const uint32 c) noexcept - { - static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 }; - - return c < sizeof (legalChars) * 8 - && (legalChars [c >> 3] & (1 << (c & 7))) != 0; - } - - static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines) - { - String::CharPointerType t (text.getCharPointer()); - - for (;;) - { - const uint32 character = (uint32) t.getAndAdvance(); - - if (character == 0) - break; - - if (isLegalXmlChar (character)) - { - outputStream << (char) character; - } - else - { - switch (character) - { - case '&': outputStream << "&"; break; - case '"': outputStream << """; break; - case '>': outputStream << ">"; break; - case '<': outputStream << "<"; break; - - case '\n': - case '\r': - if (! changeNewLines) - { - outputStream << (char) character; - break; - } - // Note: deliberate fall-through here! - default: - outputStream << "&#" << ((int) character) << ';'; - break; - } - } - } - } - - static void writeSpaces (OutputStream& out, const size_t numSpaces) - { - out.writeRepeatedByte (' ', numSpaces); - } -} - -void XmlElement::writeElementAsText (OutputStream& outputStream, - const int indentationLevel, - const int lineWrapLength) const -{ - using namespace XmlOutputFunctions; - - if (indentationLevel >= 0) - writeSpaces (outputStream, (size_t) indentationLevel); - - if (! isTextElement()) - { - outputStream.writeByte ('<'); - outputStream << tagName; - - { - const size_t attIndent = (size_t) (indentationLevel + tagName.length() + 1); - int lineLen = 0; - - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - { - if (lineLen > lineWrapLength && indentationLevel >= 0) - { - outputStream << newLine; - writeSpaces (outputStream, attIndent); - lineLen = 0; - } - - const int64 startPos = outputStream.getPosition(); - outputStream.writeByte (' '); - outputStream << att->name; - outputStream.write ("=\"", 2); - escapeIllegalXmlChars (outputStream, att->value, true); - outputStream.writeByte ('"'); - lineLen += (int) (outputStream.getPosition() - startPos); - } - } - - if (firstChildElement != nullptr) - { - outputStream.writeByte ('>'); - - bool lastWasTextNode = false; - - for (XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem) - { - if (child->isTextElement()) - { - escapeIllegalXmlChars (outputStream, child->getText(), false); - lastWasTextNode = true; - } - else - { - if (indentationLevel >= 0 && ! lastWasTextNode) - outputStream << newLine; - - child->writeElementAsText (outputStream, - lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength); - lastWasTextNode = false; - } - } - - if (indentationLevel >= 0 && ! lastWasTextNode) - { - outputStream << newLine; - writeSpaces (outputStream, (size_t) indentationLevel); - } - - outputStream.write ("'); - } - else - { - outputStream.write ("/>", 2); - } - } - else - { - escapeIllegalXmlChars (outputStream, getText(), false); - } -} - -String XmlElement::createDocument (const String& dtdToUse, - const bool allOnOneLine, - const bool includeXmlHeader, - const String& encodingType, - const int lineWrapLength) const -{ - MemoryOutputStream mem (2048); - writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength); - - return mem.toUTF8(); -} - -void XmlElement::writeToStream (OutputStream& output, - const String& dtdToUse, - const bool allOnOneLine, - const bool includeXmlHeader, - const String& encodingType, - const int lineWrapLength) const -{ - using namespace XmlOutputFunctions; - - if (includeXmlHeader) - { - output << ""; - - if (allOnOneLine) - output.writeByte (' '); - else - output << newLine << newLine; - } - - if (dtdToUse.isNotEmpty()) - { - output << dtdToUse; - - if (allOnOneLine) - output.writeByte (' '); - else - output << newLine; - } - - writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength); - - if (! allOnOneLine) - output << newLine; -} - -bool XmlElement::writeToFile (const File& file, - const String& dtdToUse, - const String& encodingType, - const int lineWrapLength) const -{ - TemporaryFile tempFile (file); - - { - FileOutputStream out (tempFile.getFile()); - - if (! out.openedOk()) - return false; - - writeToStream (out, dtdToUse, false, true, encodingType, lineWrapLength); - } - - return tempFile.overwriteTargetFileWithTemporary(); -} - -//============================================================================== -bool XmlElement::hasTagName (const String& possibleTagName) const noexcept -{ - const bool matches = tagName.equalsIgnoreCase (possibleTagName); - - // XML tags should be case-sensitive, so although this method allows a - // case-insensitive match to pass, you should try to avoid this. - bassert ((! matches) || tagName == possibleTagName); - - return matches; -} - -String XmlElement::getNamespace() const -{ - return tagName.upToFirstOccurrenceOf (":", false, false); -} - -String XmlElement::getTagNameWithoutNamespace() const -{ - return tagName.fromLastOccurrenceOf (":", false, false); -} - -bool XmlElement::hasTagNameIgnoringNamespace (const String& possibleTagName) const -{ - return hasTagName (possibleTagName) || getTagNameWithoutNamespace() == possibleTagName; -} - -XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const -{ - XmlElement* e = nextListItem; - - while (e != nullptr && ! e->hasTagName (requiredTagName)) - e = e->nextListItem; - - return e; -} - -//============================================================================== -int XmlElement::getNumAttributes() const noexcept -{ - return attributes.size(); -} - -const String& XmlElement::getAttributeName (const int index) const noexcept -{ - const XmlAttributeNode* const att = attributes [index]; - return att != nullptr ? att->name : String::empty; -} - -const String& XmlElement::getAttributeValue (const int index) const noexcept -{ - const XmlAttributeNode* const att = attributes [index]; - return att != nullptr ? att->value : String::empty; -} - -bool XmlElement::hasAttribute (const String& attributeName) const noexcept -{ - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - if (att->hasName (attributeName)) - return true; - - return false; -} - -//============================================================================== -const String& XmlElement::getStringAttribute (const String& attributeName) const noexcept -{ - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - if (att->hasName (attributeName)) - return att->value; - - return String::empty; -} - -String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const -{ - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - if (att->hasName (attributeName)) - return att->value; - - return defaultReturnValue; -} - -int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const -{ - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - if (att->hasName (attributeName)) - return att->value.getIntValue(); - - return defaultReturnValue; -} - -double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const -{ - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - if (att->hasName (attributeName)) - return att->value.getDoubleValue(); - - return defaultReturnValue; -} - -bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const -{ - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - { - if (att->hasName (attributeName)) - { - const beast_wchar firstChar = *(att->value.getCharPointer().findEndOfWhitespace()); - - return firstChar == '1' - || firstChar == 't' - || firstChar == 'y' - || firstChar == 'T' - || firstChar == 'Y'; - } - } - - return defaultReturnValue; -} - -bool XmlElement::compareAttribute (const String& attributeName, - const String& stringToCompareAgainst, - const bool ignoreCase) const noexcept -{ - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - if (att->hasName (attributeName)) - return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst) - : att->value == stringToCompareAgainst; - - return false; -} - -//============================================================================== -void XmlElement::setAttribute (const String& attributeName, const String& value) -{ - if (attributes == nullptr) - { - attributes = new XmlAttributeNode (attributeName, value); - } - else - { - for (XmlAttributeNode* att = attributes; ; att = att->nextListItem) - { - if (att->hasName (attributeName)) - { - att->value = value; - break; - } - - if (att->nextListItem == nullptr) - { - att->nextListItem = new XmlAttributeNode (attributeName, value); - break; - } - } - } -} - -void XmlElement::setAttribute (const String& attributeName, const int number) -{ - setAttribute (attributeName, String (number)); -} - -void XmlElement::setAttribute (const String& attributeName, const double number) -{ - setAttribute (attributeName, String (number, 20)); -} - -void XmlElement::removeAttribute (const String& attributeName) noexcept -{ - for (LinkedListPointer* att = &attributes; - att->get() != nullptr; - att = &(att->get()->nextListItem)) - { - if (att->get()->hasName (attributeName)) - { - delete att->removeNext(); - break; - } - } -} - -void XmlElement::removeAllAttributes() noexcept -{ - attributes.deleteAll(); -} - -//============================================================================== -int XmlElement::getNumChildElements() const noexcept -{ - return firstChildElement.size(); -} - -XmlElement* XmlElement::getChildElement (const int index) const noexcept -{ - return firstChildElement [index].get(); -} - -XmlElement* XmlElement::getChildByName (const String& childName) const noexcept -{ - for (XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem) - if (child->hasTagName (childName)) - return child; - - return nullptr; -} - -void XmlElement::addChildElement (XmlElement* const newNode) noexcept -{ - if (newNode != nullptr) - firstChildElement.append (newNode); -} - -void XmlElement::insertChildElement (XmlElement* const newNode, - int indexToInsertAt) noexcept -{ - if (newNode != nullptr) - { - removeChildElement (newNode, false); - firstChildElement.insertAtIndex (indexToInsertAt, newNode); - } -} - -XmlElement* XmlElement::createNewChildElement (const String& childTagName) -{ - XmlElement* const newElement = new XmlElement (childTagName); - addChildElement (newElement); - return newElement; -} - -bool XmlElement::replaceChildElement (XmlElement* const currentChildElement, - XmlElement* const newNode) noexcept -{ - if (newNode != nullptr) - { - if (LinkedListPointer* const p = firstChildElement.findPointerTo (currentChildElement)) - { - if (currentChildElement != newNode) - delete p->replaceNext (newNode); - - return true; - } - } - - return false; -} - -void XmlElement::removeChildElement (XmlElement* const childToRemove, - const bool shouldDeleteTheChild) noexcept -{ - if (childToRemove != nullptr) - { - firstChildElement.remove (childToRemove); - - if (shouldDeleteTheChild) - delete childToRemove; - } -} - -bool XmlElement::isEquivalentTo (const XmlElement* const other, - const bool ignoreOrderOfAttributes) const noexcept -{ - if (this != other) - { - if (other == nullptr || tagName != other->tagName) - return false; - - if (ignoreOrderOfAttributes) - { - int totalAtts = 0; - - for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem) - { - if (! other->compareAttribute (att->name, att->value)) - return false; - - ++totalAtts; - } - - if (totalAtts != other->getNumAttributes()) - return false; - } - else - { - const XmlAttributeNode* thisAtt = attributes; - const XmlAttributeNode* otherAtt = other->attributes; - - for (;;) - { - if (thisAtt == nullptr || otherAtt == nullptr) - { - if (thisAtt == otherAtt) // both 0, so it's a match - break; - - return false; - } - - if (thisAtt->name != otherAtt->name - || thisAtt->value != otherAtt->value) - { - return false; - } - - thisAtt = thisAtt->nextListItem; - otherAtt = otherAtt->nextListItem; - } - } - - const XmlElement* thisChild = firstChildElement; - const XmlElement* otherChild = other->firstChildElement; - - for (;;) - { - if (thisChild == nullptr || otherChild == nullptr) - { - if (thisChild == otherChild) // both 0, so it's a match - break; - - return false; - } - - if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes)) - return false; - - thisChild = thisChild->nextListItem; - otherChild = otherChild->nextListItem; - } - } - - return true; -} - -void XmlElement::deleteAllChildElements() noexcept -{ - firstChildElement.deleteAll(); -} - -void XmlElement::deleteAllChildElementsWithTagName (const String& name) noexcept -{ - for (XmlElement* child = firstChildElement; child != nullptr;) - { - XmlElement* const nextChild = child->nextListItem; - - if (child->hasTagName (name)) - removeChildElement (child, true); - - child = nextChild; - } -} - -bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const noexcept -{ - return firstChildElement.contains (possibleChild); -} - -XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) noexcept -{ - if (this == elementToLookFor || elementToLookFor == nullptr) - return nullptr; - - for (XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem) - { - if (elementToLookFor == child) - return this; - - if (XmlElement* const found = child->findParentElementOf (elementToLookFor)) - return found; - } - - return nullptr; -} - -void XmlElement::getChildElementsAsArray (XmlElement** elems) const noexcept -{ - firstChildElement.copyToArray (elems); -} - -void XmlElement::reorderChildElements (XmlElement** const elems, const int num) noexcept -{ - XmlElement* e = firstChildElement = elems[0]; - - for (int i = 1; i < num; ++i) - { - e->nextListItem = elems[i]; - e = e->nextListItem; - } - - e->nextListItem = nullptr; -} - -//============================================================================== -bool XmlElement::isTextElement() const noexcept -{ - return tagName.isEmpty(); -} - -static const String beast_xmltextContentAttributeName ("text"); - -const String& XmlElement::getText() const noexcept -{ - bassert (isTextElement()); // you're trying to get the text from an element that - // isn't actually a text element.. If this contains text sub-nodes, you - // probably want to use getAllSubText instead. - - return getStringAttribute (beast_xmltextContentAttributeName); -} - -void XmlElement::setText (const String& newText) -{ - if (isTextElement()) - setAttribute (beast_xmltextContentAttributeName, newText); - else - bassertfalse; // you can only change the text in a text element, not a normal one. -} - -String XmlElement::getAllSubText() const -{ - if (isTextElement()) - return getText(); - - MemoryOutputStream mem (1024); - - for (const XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem) - mem << child->getAllSubText(); - - return mem.toUTF8(); -} - -String XmlElement::getChildElementAllSubText (const String& childTagName, - const String& defaultReturnValue) const -{ - if (const XmlElement* const child = getChildByName (childTagName)) - return child->getAllSubText(); - - return defaultReturnValue; -} - -XmlElement* XmlElement::createTextElement (const String& text) -{ - XmlElement* const e = new XmlElement ((int) 0); - e->setAttribute (beast_xmltextContentAttributeName, text); - return e; -} - -void XmlElement::addTextElement (const String& text) -{ - addChildElement (createTextElement (text)); -} - -void XmlElement::deleteAllTextElements() noexcept -{ - for (XmlElement* child = firstChildElement; child != nullptr;) - { - XmlElement* const next = child->nextListItem; - - if (child->isTextElement()) - removeChildElement (child, true); - - child = next; - } -} - -} // namespace beast diff --git a/src/beast/modules/beast_core/xml/XmlElement.h b/src/beast/modules/beast_core/xml/XmlElement.h deleted file mode 100644 index 34de5227a1..0000000000 --- a/src/beast/modules/beast_core/xml/XmlElement.h +++ /dev/null @@ -1,730 +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_XMLELEMENT_H_INCLUDED -#define BEAST_XMLELEMENT_H_INCLUDED - -namespace beast -{ - -//============================================================================== -/** A handy macro to make it easy to iterate all the child elements in an XmlElement. - - The parentXmlElement should be a reference to the parent XML, and the childElementVariableName - will be the name of a pointer to each child element. - - E.g. @code - XmlElement* myParentXml = createSomeKindOfXmlDocument(); - - forEachXmlChildElement (*myParentXml, child) - { - if (child->hasTagName ("FOO")) - doSomethingWithXmlElement (child); - } - - @endcode - - @see forEachXmlChildElementWithTagName -*/ -#define beast_forEachXmlChildElement(parentXmlElement, childElementVariableName) \ -\ - for (beast::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \ - childElementVariableName != nullptr; \ - childElementVariableName = childElementVariableName->getNextElement()) - -/** A macro that makes it easy to iterate all the child elements of an XmlElement - which have a specified tag. - - This does the same job as the forEachXmlChildElement macro, but only for those - elements that have a particular tag name. - - The parentXmlElement should be a reference to the parent XML, and the childElementVariableName - will be the name of a pointer to each child element. The requiredTagName is the - tag name to match. - - E.g. @code - XmlElement* myParentXml = createSomeKindOfXmlDocument(); - - forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG") - { - // the child object is now guaranteed to be a element.. - doSomethingWithMYTAGElement (child); - } - - @endcode - - @see forEachXmlChildElement -*/ -#define beast_forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \ -\ - for (beast::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \ - childElementVariableName != nullptr; \ - childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName)) - - -//============================================================================== -/** Used to build a tree of elements representing an XML document. - - An XML document can be parsed into a tree of XmlElements, each of which - represents an XML tag structure, and which may itself contain other - nested elements. - - An XmlElement can also be converted back into a text document, and has - lots of useful methods for manipulating its attributes and sub-elements, - so XmlElements can actually be used as a handy general-purpose data - structure. - - Here's an example of parsing some elements: @code - // check we're looking at the right kind of document.. - if (myElement->hasTagName ("ANIMALS")) - { - // now we'll iterate its sub-elements looking for 'giraffe' elements.. - forEachXmlChildElement (*myElement, e) - { - if (e->hasTagName ("GIRAFFE")) - { - // found a giraffe, so use some of its attributes.. - - String giraffeName = e->getStringAttribute ("name"); - int giraffeAge = e->getIntAttribute ("age"); - bool isFriendly = e->getBoolAttribute ("friendly"); - } - } - } - @endcode - - And here's an example of how to create an XML document from scratch: @code - // create an outer node called "ANIMALS" - XmlElement animalsList ("ANIMALS"); - - for (int i = 0; i < numAnimals; ++i) - { - // create an inner element.. - XmlElement* giraffe = new XmlElement ("GIRAFFE"); - - giraffe->setAttribute ("name", "nigel"); - giraffe->setAttribute ("age", 10); - giraffe->setAttribute ("friendly", true); - - // ..and add our new element to the parent node - animalsList.addChildElement (giraffe); - } - - // now we can turn the whole thing into a text document.. - String myXmlDoc = animalsList.createDocument (String::empty); - @endcode - - @see XmlDocument -*/ -class BEAST_API XmlElement : LeakChecked -{ -public: - //============================================================================== - /** Creates an XmlElement with this tag name. */ - explicit XmlElement (const String& tagName) noexcept; - - /** Creates a (deep) copy of another element. */ - XmlElement (const XmlElement& other); - - /** Creates a (deep) copy of another element. */ - XmlElement& operator= (const XmlElement& other); - - #if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS - XmlElement (XmlElement&& other) noexcept; - XmlElement& operator= (XmlElement&& other) noexcept; - #endif - - /** Deleting an XmlElement will also delete all its child elements. */ - ~XmlElement() noexcept; - - //============================================================================== - /** Compares two XmlElements to see if they contain the same text and attiributes. - - The elements are only considered equivalent if they contain the same attiributes - with the same values, and have the same sub-nodes. - - @param other the other element to compare to - @param ignoreOrderOfAttributes if true, this means that two elements with the - same attributes in a different order will be - considered the same; if false, the attributes must - be in the same order as well - */ - bool isEquivalentTo (const XmlElement* other, - bool ignoreOrderOfAttributes) const noexcept; - - //============================================================================== - /** Returns an XML text document that represents this element. - - The string returned can be parsed to recreate the same XmlElement that - was used to create it. - - @param dtdToUse the DTD to add to the document - @param allOnOneLine if true, this means that the document will not contain any - linefeeds, so it'll be smaller but not very easy to read. - @param includeXmlHeader whether to add the ", this would return "MOOSE". - @see hasTagName - */ - inline const String& getTagName() const noexcept { return tagName; } - - /** Returns the namespace portion of the tag-name, or an empty string if none is specified. */ - String getNamespace() const; - - /** Returns the part of the tag-name that follows any namespace declaration. */ - String getTagNameWithoutNamespace() const; - - /** Tests whether this element has a particular tag name. - @param possibleTagName the tag name you're comparing it with - @see getTagName - */ - bool hasTagName (const String& possibleTagName) const noexcept; - - /** Tests whether this element has a particular tag name, ignoring any XML namespace prefix. - So a test for e.g. "xyz" will return true for "xyz" and also "foo:xyz", "bar::xyz", etc. - @see getTagName - */ - bool hasTagNameIgnoringNamespace (const String& possibleTagName) const; - - //============================================================================== - /** Returns the number of XML attributes this element contains. - - E.g. for an element such as \, this would - return 2. - */ - int getNumAttributes() const noexcept; - - /** Returns the name of one of the elements attributes. - - E.g. for an element such as \, then - getAttributeName(1) would return "antlers". - - @see getAttributeValue, getStringAttribute - */ - const String& getAttributeName (int attributeIndex) const noexcept; - - /** Returns the value of one of the elements attributes. - - E.g. for an element such as \, then - getAttributeName(1) would return "2". - - @see getAttributeName, getStringAttribute - */ - const String& getAttributeValue (int attributeIndex) const noexcept; - - //============================================================================== - // Attribute-handling methods.. - - /** Checks whether the element contains an attribute with a certain name. */ - bool hasAttribute (const String& attributeName) const noexcept; - - /** Returns the value of a named attribute. - - @param attributeName the name of the attribute to look up - */ - const String& getStringAttribute (const String& attributeName) const noexcept; - - /** Returns the value of a named attribute. - - @param attributeName the name of the attribute to look up - @param defaultReturnValue a value to return if the element doesn't have an attribute - with this name - */ - String getStringAttribute (const String& attributeName, - const String& defaultReturnValue) const; - - /** Compares the value of a named attribute with a value passed-in. - - @param attributeName the name of the attribute to look up - @param stringToCompareAgainst the value to compare it with - @param ignoreCase whether the comparison should be case-insensitive - @returns true if the value of the attribute is the same as the string passed-in; - false if it's different (or if no such attribute exists) - */ - bool compareAttribute (const String& attributeName, - const String& stringToCompareAgainst, - bool ignoreCase = false) const noexcept; - - /** Returns the value of a named attribute as an integer. - - This will try to find the attribute and convert it to an integer (using - the String::getIntValue() method). - - @param attributeName the name of the attribute to look up - @param defaultReturnValue a value to return if the element doesn't have an attribute - with this name - @see setAttribute - */ - int getIntAttribute (const String& attributeName, - int defaultReturnValue = 0) const; - - /** Returns the value of a named attribute as floating-point. - - This will try to find the attribute and convert it to an integer (using - the String::getDoubleValue() method). - - @param attributeName the name of the attribute to look up - @param defaultReturnValue a value to return if the element doesn't have an attribute - with this name - @see setAttribute - */ - double getDoubleAttribute (const String& attributeName, - double defaultReturnValue = 0.0) const; - - /** Returns the value of a named attribute as a boolean. - - This will try to find the attribute and interpret it as a boolean. To do this, - it'll return true if the value is "1", "true", "y", etc, or false for other - values. - - @param attributeName the name of the attribute to look up - @param defaultReturnValue a value to return if the element doesn't have an attribute - with this name - */ - bool getBoolAttribute (const String& attributeName, - bool defaultReturnValue = false) const; - - /** Adds a named attribute to the element. - - If the element already contains an attribute with this name, it's value will - be updated to the new value. If there's no such attribute yet, a new one will - be added. - - Note that there are other setAttribute() methods that take integers, - doubles, etc. to make it easy to store numbers. - - @param attributeName the name of the attribute to set - @param newValue the value to set it to - @see removeAttribute - */ - void setAttribute (const String& attributeName, - const String& newValue); - - /** Adds a named attribute to the element, setting it to an integer value. - - If the element already contains an attribute with this name, it's value will - be updated to the new value. If there's no such attribute yet, a new one will - be added. - - Note that there are other setAttribute() methods that take integers, - doubles, etc. to make it easy to store numbers. - - @param attributeName the name of the attribute to set - @param newValue the value to set it to - */ - void setAttribute (const String& attributeName, - int newValue); - - /** Adds a named attribute to the element, setting it to a floating-point value. - - If the element already contains an attribute with this name, it's value will - be updated to the new value. If there's no such attribute yet, a new one will - be added. - - Note that there are other setAttribute() methods that take integers, - doubles, etc. to make it easy to store numbers. - - @param attributeName the name of the attribute to set - @param newValue the value to set it to - */ - void setAttribute (const String& attributeName, - double newValue); - - /** Removes a named attribute from the element. - - @param attributeName the name of the attribute to remove - @see removeAllAttributes - */ - void removeAttribute (const String& attributeName) noexcept; - - /** Removes all attributes from this element. - */ - void removeAllAttributes() noexcept; - - //============================================================================== - // Child element methods.. - - /** Returns the first of this element's sub-elements. - - see getNextElement() for an example of how to iterate the sub-elements. - - @see forEachXmlChildElement - */ - XmlElement* getFirstChildElement() const noexcept { return firstChildElement; } - - /** Returns the next of this element's siblings. - - This can be used for iterating an element's sub-elements, e.g. - @code - XmlElement* child = myXmlDocument->getFirstChildElement(); - - while (child != nullptr) - { - ...do stuff with this child.. - - child = child->getNextElement(); - } - @endcode - - Note that when iterating the child elements, some of them might be - text elements as well as XML tags - use isTextElement() to work this - out. - - Also, it's much easier and neater to use this method indirectly via the - forEachXmlChildElement macro. - - @returns the sibling element that follows this one, or zero if this is the last - element in its parent - - @see getNextElement, isTextElement, forEachXmlChildElement - */ - inline XmlElement* getNextElement() const noexcept { return nextListItem; } - - /** Returns the next of this element's siblings which has the specified tag - name. - - This is like getNextElement(), but will scan through the list until it - finds an element with the given tag name. - - @see getNextElement, forEachXmlChildElementWithTagName - */ - XmlElement* getNextElementWithTagName (const String& requiredTagName) const; - - /** Returns the number of sub-elements in this element. - - @see getChildElement - */ - int getNumChildElements() const noexcept; - - /** Returns the sub-element at a certain index. - - It's not very efficient to iterate the sub-elements by index - see - getNextElement() for an example of how best to iterate. - - @returns the n'th child of this element, or nullptr if the index is out-of-range - @see getNextElement, isTextElement, getChildByName - */ - XmlElement* getChildElement (int index) const noexcept; - - /** Returns the first sub-element with a given tag-name. - - @param tagNameToLookFor the tag name of the element you want to find - @returns the first element with this tag name, or nullptr if none is found - @see getNextElement, isTextElement, getChildElement - */ - XmlElement* getChildByName (const String& tagNameToLookFor) const noexcept; - - //============================================================================== - /** Appends an element to this element's list of children. - - Child elements are deleted automatically when their parent is deleted, so - make sure the object that you pass in will not be deleted by anything else, - and make sure it's not already the child of another element. - - @see getFirstChildElement, getNextElement, getNumChildElements, - getChildElement, removeChildElement - */ - void addChildElement (XmlElement* newChildElement) noexcept; - - /** Inserts an element into this element's list of children. - - Child elements are deleted automatically when their parent is deleted, so - make sure the object that you pass in will not be deleted by anything else, - and make sure it's not already the child of another element. - - @param newChildNode the element to add - @param indexToInsertAt the index at which to insert the new element - if this is - below zero, it will be added to the end of the list - @see addChildElement, insertChildElement - */ - void insertChildElement (XmlElement* newChildNode, - int indexToInsertAt) noexcept; - - /** Creates a new element with the given name and returns it, after adding it - as a child element. - - This is a handy method that means that instead of writing this: - @code - XmlElement* newElement = new XmlElement ("foobar"); - myParentElement->addChildElement (newElement); - @endcode - - ..you could just write this: - @code - XmlElement* newElement = myParentElement->createNewChildElement ("foobar"); - @endcode - */ - XmlElement* createNewChildElement (const String& tagName); - - /** Replaces one of this element's children with another node. - - If the current element passed-in isn't actually a child of this element, - this will return false and the new one won't be added. Otherwise, the - existing element will be deleted, replaced with the new one, and it - will return true. - */ - bool replaceChildElement (XmlElement* currentChildElement, - XmlElement* newChildNode) noexcept; - - /** Removes a child element. - - @param childToRemove the child to look for and remove - @param shouldDeleteTheChild if true, the child will be deleted, if false it'll - just remove it - */ - void removeChildElement (XmlElement* childToRemove, - bool shouldDeleteTheChild) noexcept; - - /** Deletes all the child elements in the element. - - @see removeChildElement, deleteAllChildElementsWithTagName - */ - void deleteAllChildElements() noexcept; - - /** Deletes all the child elements with a given tag name. - - @see removeChildElement - */ - void deleteAllChildElementsWithTagName (const String& tagName) noexcept; - - /** Returns true if the given element is a child of this one. */ - bool containsChildElement (const XmlElement* possibleChild) const noexcept; - - /** Recursively searches all sub-elements to find one that contains the specified - child element. - */ - XmlElement* findParentElementOf (const XmlElement* elementToLookFor) noexcept; - - //============================================================================== - /** Sorts the child elements using a comparator. - - This will use a comparator object to sort the elements into order. The object - passed must have a method of the form: - @code - int compareElements (const XmlElement* first, const XmlElement* second); - @endcode - - ..and this method must return: - - a value of < 0 if the first comes before the second - - a value of 0 if the two objects are equivalent - - a value of > 0 if the second comes before the first - - To improve performance, the compareElements() method can be declared as static or const. - - @param comparator the comparator to use for comparing elements. - @param retainOrderOfEquivalentItems if this is true, then items which the comparator - says are equivalent will be kept in the order in which they - currently appear in the array. This is slower to perform, but - may be important in some cases. If it's false, a faster algorithm - is used, but equivalent elements may be rearranged. - */ - template - void sortChildElements (ElementComparator& comparator, - bool retainOrderOfEquivalentItems = false) - { - const int num = getNumChildElements(); - - if (num > 1) - { - HeapBlock elems ((size_t) num); - getChildElementsAsArray (elems); - sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems); - reorderChildElements (elems, num); - } - } - - //============================================================================== - /** Returns true if this element is a section of text. - - Elements can either be an XML tag element or a secton of text, so this - is used to find out what kind of element this one is. - - @see getAllText, addTextElement, deleteAllTextElements - */ - bool isTextElement() const noexcept; - - /** Returns the text for a text element. - - Note that if you have an element like this: - - @codehello@endcode - - then calling getText on the "xyz" element won't return "hello", because that is - actually stored in a special text sub-element inside the xyz element. To get the - "hello" string, you could either call getText on the (unnamed) sub-element, or - use getAllSubText() to do this automatically. - - Note that leading and trailing whitespace will be included in the string - to remove - if, just call String::trim() on the result. - - @see isTextElement, getAllSubText, getChildElementAllSubText - */ - const String& getText() const noexcept; - - /** Sets the text in a text element. - - Note that this is only a valid call if this element is a text element. If it's - not, then no action will be performed. If you're trying to add text inside a normal - element, you probably want to use addTextElement() instead. - */ - void setText (const String& newText); - - /** Returns all the text from this element's child nodes. - - This iterates all the child elements and when it finds text elements, - it concatenates their text into a big string which it returns. - - E.g. @codehello there world@endcode - if you called getAllSubText on the "xyz" element, it'd return "hello there world". - - Note that leading and trailing whitespace will be included in the string - to remove - if, just call String::trim() on the result. - - @see isTextElement, getChildElementAllSubText, getText, addTextElement - */ - String getAllSubText() const; - - /** Returns all the sub-text of a named child element. - - If there is a child element with the given tag name, this will return - all of its sub-text (by calling getAllSubText() on it). If there is - no such child element, this will return the default string passed-in. - - @see getAllSubText - */ - String getChildElementAllSubText (const String& childTagName, - const String& defaultReturnValue) const; - - /** Appends a section of text to this element. - - @see isTextElement, getText, getAllSubText - */ - void addTextElement (const String& text); - - /** Removes all the text elements from this element. - - @see isTextElement, getText, getAllSubText, addTextElement - */ - void deleteAllTextElements() noexcept; - - /** Creates a text element that can be added to a parent element. - */ - static XmlElement* createTextElement (const String& text); - - //============================================================================== -private: - struct XmlAttributeNode - { - XmlAttributeNode (const XmlAttributeNode&) noexcept; - XmlAttributeNode (const String& name, const String& value) noexcept; - - LinkedListPointer nextListItem; - String name, value; - - bool hasName (const String&) const noexcept; - - private: - XmlAttributeNode& operator= (const XmlAttributeNode&); - }; - - friend class XmlDocument; - friend class LinkedListPointer ; - friend class LinkedListPointer ; - friend class LinkedListPointer ::Appender; - - LinkedListPointer nextListItem; - LinkedListPointer firstChildElement; - LinkedListPointer attributes; - String tagName; - - XmlElement (int) noexcept; - void copyChildrenAndAttributesFrom (const XmlElement&); - void writeElementAsText (OutputStream&, int indentationLevel, int lineWrapLength) const; - void getChildElementsAsArray (XmlElement**) const noexcept; - void reorderChildElements (XmlElement**, int) noexcept; -}; - -} // namespace beast - -#endif // BEAST_XMLELEMENT_H_INCLUDED diff --git a/src/beast/modules/beast_sqdb/api/backend.h b/src/beast/modules/beast_sqdb/api/backend.h index d36063251c..09911ba8c7 100644 --- a/src/beast/modules/beast_sqdb/api/backend.h +++ b/src/beast/modules/beast_sqdb/api/backend.h @@ -60,11 +60,15 @@ #ifndef BEAST_SQDB_BACKEND_H_INCLUDED #define BEAST_SQDB_BACKEND_H_INCLUDED -namespace sqdb -{ +#include -namespace detail -{ +namespace beast { +namespace sqdb { + +namespace detail { + +//signed char +//wchar_t // supported standard types for intos and uses enum exchange_type @@ -72,13 +76,12 @@ enum exchange_type x_null, // only for input variables x_bool, - - x_char, x_uchar, - x_short, x_ushort, - x_int, x_uint, - x_long, x_ulong, - x_int64, x_uint64, - x_float, x_double, + x_char, x_uchar, + x_short, x_ushort, + x_int, x_uint, + x_long, x_ulong, + x_longlong, x_ulonglong, + x_float, x_double, x_longdouble, x_cstring, // null terminated char*, only valid for use_type x_cwstring, // null terminated wchar*, only valid for use_type @@ -91,7 +94,7 @@ enum exchange_type x_blob }; -} +} // detail // the enum type for indicator variables enum indicator @@ -104,8 +107,9 @@ enum indicator // sqlite row id //typedef sqlite3_int64 rowid; -typedef int64 rowid; +typedef std::int64_t rowid; -} +} // sqdb +} // beast #endif diff --git a/src/beast/modules/beast_sqdb/api/blob.h b/src/beast/modules/beast_sqdb/api/blob.h index 5e4642fd5a..6f3c16893c 100644 --- a/src/beast/modules/beast_sqdb/api/blob.h +++ b/src/beast/modules/beast_sqdb/api/blob.h @@ -60,8 +60,8 @@ #ifndef BEAST_SQDB_BLOB_H_INCLUDED #define BEAST_SQDB_BLOB_H_INCLUDED -namespace sqdb -{ +namespace beast { +namespace sqdb { // BLOB interface class blob @@ -86,6 +86,7 @@ private: sqlite3_blob* m_blob; }; -} +} // sqdb +} // beast #endif diff --git a/src/beast/modules/beast_sqdb/api/into.h b/src/beast/modules/beast_sqdb/api/into.h index 7cccd7fc2d..4c793dd178 100644 --- a/src/beast/modules/beast_sqdb/api/into.h +++ b/src/beast/modules/beast_sqdb/api/into.h @@ -60,8 +60,8 @@ #ifndef BEAST_SQDB_INTO_H_INCLUDED #define BEAST_SQDB_INTO_H_INCLUDED -namespace sqdb -{ +namespace beast { +namespace sqdb { template detail::into_type_ptr into(T& t) @@ -77,6 +77,7 @@ detail::into_type_ptr into(T& t, indicator& ind) typename detail::exchange_traits::type_family()); } -} +} // sqdb +} // beast #endif \ No newline at end of file diff --git a/src/beast/modules/beast_sqdb/api/session.h b/src/beast/modules/beast_sqdb/api/session.h index 3a77093764..56d04978ef 100644 --- a/src/beast/modules/beast_sqdb/api/session.h +++ b/src/beast/modules/beast_sqdb/api/session.h @@ -60,8 +60,11 @@ #ifndef BEAST_SQDB_SESSION_H_INCLUDED #define BEAST_SQDB_SESSION_H_INCLUDED -namespace sqdb -{ +#include "../../../beast/smart_ptr/SharedPtr.h" +#include "../../beast_core/memory/SharedSingleton.h" + +namespace beast { +namespace sqdb { /*============================================================================*/ /** @@ -145,6 +148,7 @@ private: bool m_bGotData; }; -} +} // sqdb +} // beast #endif diff --git a/src/beast/modules/beast_sqdb/api/statement.h b/src/beast/modules/beast_sqdb/api/statement.h index 5900e32c5f..99632b4ecf 100644 --- a/src/beast/modules/beast_sqdb/api/statement.h +++ b/src/beast/modules/beast_sqdb/api/statement.h @@ -60,8 +60,10 @@ #ifndef BEAST_SQDB_STATEMENT_H_INCLUDED #define BEAST_SQDB_STATEMENT_H_INCLUDED -namespace sqdb -{ +#include + +namespace beast { +namespace sqdb { // // Lightweight copyable handle to a statement. This @@ -95,9 +97,10 @@ private: void clean_up(); private: - SharedPtr m_imp; + std::shared_ptr m_imp; }; -} +} // sqdb +} // beast #endif diff --git a/src/beast/modules/beast_sqdb/api/transaction.h b/src/beast/modules/beast_sqdb/api/transaction.h index bca0ed0488..4fa050f612 100644 --- a/src/beast/modules/beast_sqdb/api/transaction.h +++ b/src/beast/modules/beast_sqdb/api/transaction.h @@ -60,15 +60,17 @@ #ifndef BEAST_SQDB_TRANSACTION_H_INCLUDED #define BEAST_SQDB_TRANSACTION_H_INCLUDED -namespace sqdb -{ +#include "../../../beast/utility/Error.h" -class transaction : public Uncopyable +namespace beast { +namespace sqdb { + +class transaction { public: explicit transaction(session& s); ~transaction(); - + transaction& operator= (transaction const&) = delete; Error commit(); void rollback(); @@ -77,6 +79,7 @@ private: bool m_bHandled; }; -} +} // sqdb +} // beast #endif diff --git a/src/beast/modules/beast_sqdb/api/type_conversion_traits.h b/src/beast/modules/beast_sqdb/api/type_conversion_traits.h index c7b4786414..9625bd05a8 100644 --- a/src/beast/modules/beast_sqdb/api/type_conversion_traits.h +++ b/src/beast/modules/beast_sqdb/api/type_conversion_traits.h @@ -60,8 +60,12 @@ #ifndef BEAST_SQDB_TYPE_CONVERSION_TRAITS_H_INCLUDED #define BEAST_SQDB_TYPE_CONVERSION_TRAITS_H_INCLUDED -namespace sqdb -{ +#include "../../beast_core/time/Time.h" + +#include + +namespace beast { +namespace sqdb { // default conversion (copy in to out) template @@ -72,7 +76,7 @@ struct type_conversion static void from_base(base_type const& in, indicator ind, T& out) { // null not allowed - check_precondition (ind != i_null); + assert (ind != i_null); out = in; } @@ -88,7 +92,7 @@ template <> struct type_conversion