diff --git a/Builds/VisualStudio2013/RippleD.vcxproj b/Builds/VisualStudio2013/RippleD.vcxproj
index 7e8561a80f..c18f7fcbef 100644
--- a/Builds/VisualStudio2013/RippleD.vcxproj
+++ b/Builds/VisualStudio2013/RippleD.vcxproj
@@ -274,8 +274,6 @@
-
-
True
@@ -290,9 +288,6 @@
-
- True
-
@@ -300,16 +295,6 @@
True
-
- True
-
-
- True
-
-
-
-
-
@@ -515,10 +500,6 @@
-
-
-
-
@@ -561,35 +542,13 @@
-
- True
-
-
-
-
- True
-
-
-
-
- True
-
-
-
-
- True
-
-
-
True
-
-
True
@@ -602,8 +561,6 @@
-
-
@@ -636,14 +593,9 @@
-
-
True
-
- True
-
True
@@ -696,8 +648,6 @@
-
-
@@ -849,8 +799,6 @@
-
-
@@ -935,9 +883,6 @@
-
- True
-
True
@@ -1004,9 +949,6 @@
True
-
- True
-
diff --git a/Builds/VisualStudio2013/RippleD.vcxproj.filters b/Builds/VisualStudio2013/RippleD.vcxproj.filters
index 832bb91b87..576146d90b 100644
--- a/Builds/VisualStudio2013/RippleD.vcxproj.filters
+++ b/Builds/VisualStudio2013/RippleD.vcxproj.filters
@@ -789,9 +789,6 @@
beast\crypto
-
- beast\crypto
-
beast\crypto
@@ -807,9 +804,6 @@
beast\crypto\impl\sha2
-
- beast\crypto\impl
-
beast\crypto
@@ -819,18 +813,6 @@
beast\crypto\tests
-
- beast\crypto\tests
-
-
- beast\crypto\tests
-
-
- beast\crypto
-
-
- beast\crypto
-
beast\cxx14
@@ -1092,12 +1074,6 @@
beast\module\core\containers
-
- beast\module\core\containers
-
-
- beast\module\core\containers
-
beast\module\core
@@ -1149,42 +1125,15 @@
beast\module\core\files
-
- beast\module\core\files
-
-
- beast\module\core\files
-
-
- beast\module\core\files
-
-
- beast\module\core\files
-
-
- beast\module\core\files
-
-
- beast\module\core\files
-
-
- beast\module\core\logging
-
beast\module\core\logging
-
- beast\module\core\maths
-
beast\module\core\maths
beast\module\core\maths
-
- beast\module\core\maths
-
beast\module\core\memory
@@ -1200,9 +1149,6 @@
beast\module\core\misc
-
- beast\module\core\misc
-
beast\module\core\native
@@ -1242,15 +1188,9 @@
beast\module\core\native
-
- beast\module\core\native
-
beast\module\core\native
-
- beast\module\core\native
-
beast\module\core\native
@@ -1314,9 +1254,6 @@
beast\module\core\threads
-
- beast\module\core\threads
-
beast\module\core\threads
@@ -1506,9 +1443,6 @@
beast\smart_ptr
-
- beast
-
beast\streams
@@ -1620,9 +1554,6 @@
beast\threads
-
- beast\threads\tests
-
beast\threads\tests
@@ -1710,9 +1641,6 @@
beast\utility\impl
-
- beast\utility\impl
-
beast\utility
diff --git a/src/BeastConfig.h b/src/BeastConfig.h
index b066800a35..b175ac3341 100644
--- a/src/BeastConfig.h
+++ b/src/BeastConfig.h
@@ -57,18 +57,6 @@
//#define BEAST_FORCE_DEBUG 1
#endif
-/** Config: BEAST_LOG_ASSERTIONS
- If this flag is enabled, the the bassert and bassertfalse macros will always
- use Logger::writeToLog() to write a message when an assertion happens.
- Enabling it will also leave this turned on in release builds. When it's
- disabled, however, the bassert and bassertfalse macros will not be compiled
- in a release build.
- @see bassert, bassertfalse, Logger
-*/
-#ifndef BEAST_LOG_ASSERTIONS
-//#define BEAST_LOG_ASSERTIONS 1
-#endif
-
/** Config: BEAST_CHECK_MEMORY_LEAKS
Enables a memory-leak check for certain objects when the app terminates.
See the LeakChecked class for more details about enabling leak checking for
diff --git a/src/beast/BeastConfig.h b/src/beast/BeastConfig.h
index 0765cc3b77..c4be12f130 100644
--- a/src/beast/BeastConfig.h
+++ b/src/beast/BeastConfig.h
@@ -55,18 +55,6 @@
//#define BEAST_FORCE_DEBUG 1
#endif
-/** Config: BEAST_LOG_ASSERTIONS
- If this flag is enabled, the the bassert and bassertfalse macros will always
- use Logger::writeToLog() to write a message when an assertion happens.
- Enabling it will also leave this turned on in release builds. When it's
- disabled, however, the bassert and bassertfalse macros will not be compiled
- in a release build.
- @see bassert, bassertfalse, Logger
-*/
-#ifndef BEAST_LOG_ASSERTIONS
-//#define BEAST_LOG_ASSERTIONS 1
-#endif
-
/** Config: BEAST_CHECK_MEMORY_LEAKS
Enables a memory-leak check for certain objects when the app terminates.
See the LeakChecked class for more details about enabling leak checking for
diff --git a/src/beast/beast/Arithmetic.h b/src/beast/beast/Arithmetic.h
index a23b926503..edc285731a 100644
--- a/src/beast/beast/Arithmetic.h
+++ b/src/beast/beast/Arithmetic.h
@@ -34,101 +34,6 @@
namespace beast {
-// Some indispensible min/max functions
-
-/** Returns the larger of two values. */
-template
-inline Type bmax (const Type a, const Type b)
- { return (a < b) ? b : a; }
-
-/** Returns the larger of three values. */
-template
-inline Type bmax (const Type a, const Type b, const Type c)
- { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
-
-/** Returns the larger of four values. */
-template
-inline Type bmax (const Type a, const Type b, const Type c, const Type d)
- { return bmax (a, bmax (b, c, d)); }
-
-/** Returns the smaller of two values. */
-template
-inline Type bmin (const Type a, const Type b)
- { return (b < a) ? b : a; }
-
-/** Returns the smaller of three values. */
-template
-inline Type bmin (const Type a, const Type b, const Type c)
- { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
-
-/** Returns the smaller of four values. */
-template
-inline Type bmin (const Type a, const Type b, const Type c, const Type d)
- { return bmin (a, bmin (b, c, d)); }
-
-/** Scans an array of values, returning the minimum value that it contains. */
-template
-const Type findMinimum (const Type* data, int numValues)
-{
- if (numValues <= 0)
- return Type();
-
- Type result (*data++);
-
- while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
- {
- const Type& v = *data++;
- if (v < result) result = v;
- }
-
- return result;
-}
-
-/** Scans an array of values, returning the maximum value that it contains. */
-template
-const Type findMaximum (const Type* values, int numValues)
-{
- if (numValues <= 0)
- return Type();
-
- Type result (*values++);
-
- while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
- {
- const Type& v = *values++;
- if (result < v) result = v;
- }
-
- return result;
-}
-
-/** Scans an array of values, returning the minimum and maximum values that it contains. */
-template
-void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
-{
- if (numValues <= 0)
- {
- lowest = Type();
- highest = Type();
- }
- else
- {
- Type mn (*values++);
- Type mx (mn);
-
- while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
- {
- const Type& v = *values++;
-
- if (mx < v) mx = v;
- if (v < mn) mn = v;
- }
-
- lowest = mn;
- highest = mx;
- }
-}
-
//==============================================================================
/** Constrains a value to keep it within a given range.
@@ -151,7 +56,8 @@ inline Type blimit (const Type lowerLimit,
const Type upperLimit,
const Type valueToConstrain) noexcept
{
- bassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
+ // if these are in the wrong order, results are unpredictable.
+ bassert (lowerLimit <= upperLimit);
return (valueToConstrain < lowerLimit) ? lowerLimit
: ((upperLimit < valueToConstrain) ? upperLimit
@@ -177,24 +83,6 @@ inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noe
return static_cast (valueToTest) < static_cast (upperLimit);
}
-/** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
- This is basically a quicker way to write:
- @code valueToTest >= 0 && valueToTest <= upperLimit
- @endcode
-*/
-template
-inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
-{
- bassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
- return Type() <= valueToTest && valueToTest <= upperLimit;
-}
-
-template <>
-inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
-{
- bassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
- return static_cast (valueToTest) <= static_cast (upperLimit);
-}
//==============================================================================
@@ -214,55 +102,6 @@ int numElementsInArray (Type (&array)[N])
return N;
}
-/** 64-bit abs function. */
-inline std::int64_t abs64 (const std::int64_t n) noexcept
-{
- return (n >= 0) ? n : -n;
-}
-
-
-//==============================================================================
-#if BEAST_MSVC
- #pragma optimize ("t", off)
- #ifndef __INTEL_COMPILER
- #pragma float_control (precise, on, push)
- #endif
-#endif
-
-/** 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.
-*/
-template
-inline int roundToInt (const FloatType value) noexcept
-{
- #ifdef __INTEL_COMPILER
- #pragma float_control (precise, on, push)
- #endif
-
- union { int asInt[2]; double asDouble; } n;
- n.asDouble = ((double) value) + 6755399441055744.0;
-
- #if BEAST_BIG_ENDIAN
- return n.asInt [1];
- #else
- return n.asInt [0];
- #endif
-}
-
-#if BEAST_MSVC
- #ifndef __INTEL_COMPILER
- #pragma float_control (pop)
- #endif
- #pragma optimize ("", on) // resets optimisations to the project defaults
-#endif
-
}
#endif
diff --git a/src/beast/beast/Atomic.h b/src/beast/beast/Atomic.h
index fcae075f4a..c2ec2d6a5f 100644
--- a/src/beast/beast/Atomic.h
+++ b/src/beast/beast/Atomic.h
@@ -25,7 +25,6 @@
#define BEAST_ATOMIC_H_INCLUDED
#include
-#include
#include
@@ -43,6 +42,10 @@ namespace beast {
template
class Atomic
{
+ // This class can only be used for types which are 32 or 64 bits in size.
+ static_assert (sizeof (Type) == 4 || sizeof (Type) == 8,
+ "Atomic arguments must be 32- or 64-bit long primitive types.");
+
public:
/** Creates a new value, initialised to zero. */
inline Atomic() noexcept
@@ -65,8 +68,6 @@ public:
/** Destructor. */
inline ~Atomic() noexcept
{
- // This class can only be used for types which are 32 or 64 bits in size.
- static_bassert (sizeof (Type) == 4 || sizeof (Type) == 8);
}
/** Atomically reads and returns the current value. */
diff --git a/src/beast/beast/Crypto.h b/src/beast/beast/Crypto.h
index 27e79e04c0..b8258ee61f 100644
--- a/src/beast/beast/Crypto.h
+++ b/src/beast/beast/Crypto.h
@@ -20,11 +20,8 @@
#ifndef BEAST_CRYPTO_H_INCLUDED
#define BEAST_CRYPTO_H_INCLUDED
-#include
#include
#include
-#include
-#include
#endif
diff --git a/src/beast/beast/StaticAssert.h b/src/beast/beast/StaticAssert.h
deleted file mode 100644
index 1c36d0bd1c..0000000000
--- a/src/beast/beast/StaticAssert.h
+++ /dev/null
@@ -1,45 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-#ifndef BEAST_STATICASSERT_H_INCLUDED
-#define BEAST_STATICASSERT_H_INCLUDED
-
-#ifndef DOXYGEN
-namespace beast
-{
- template
- struct BeastStaticAssert;
-
- template <>
- struct BeastStaticAssert
- {
- static void dummy() {}
- };
-}
-#endif
-
-/** A compile-time assertion macro.
- If the expression parameter is false, the macro will cause a compile error.
- (The actual error message that the compiler generates may be completely
- bizarre and seem to have no relation to the place where you put the
- static_assert though!)
-*/
-#define static_bassert(expression) beast::BeastStaticAssert::dummy();
-
-#endif
diff --git a/src/beast/beast/config/CompilerConfig.h b/src/beast/beast/config/CompilerConfig.h
index 7eb0e83dbb..89e2377be7 100644
--- a/src/beast/beast/config/CompilerConfig.h
+++ b/src/beast/beast/config/CompilerConfig.h
@@ -109,9 +109,12 @@ extern void beast_reportFatalError (char const* message, char const* fileName, i
/** Writes a string to the standard error stream.
This is only compiled in a debug build.
- @see Logger::outputDebugString
*/
-#define BDBG(dbgtext) { beast::String tempDbgBuf; tempDbgBuf << dbgtext; beast::Logger::outputDebugString (tempDbgBuf); }
+#define BDBG(dbgtext) { \
+ beast::String tempDbgBuf; \
+ tempDbgBuf << dbgtext; \
+ beast::outputDebugString (tempDbgBuf.toStdString ()); \
+}
#if 0
/** This will always cause an assertion failure.
diff --git a/src/beast/beast/crypto/BinaryEncoding.h b/src/beast/beast/crypto/BinaryEncoding.h
deleted file mode 100644
index 0112160eb9..0000000000
--- a/src/beast/beast/crypto/BinaryEncoding.h
+++ /dev/null
@@ -1,23 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-#ifndef BEAST_CRYPTO_BINARYENCODING_H_INCLUDED
-#define BEAST_CRYPTO_BINARYENCODING_H_INCLUDED
-
-#endif
diff --git a/src/beast/beast/crypto/Crypto.unity.cpp b/src/beast/beast/crypto/Crypto.unity.cpp
index 2e9e0f320e..95ab834c5b 100644
--- a/src/beast/beast/crypto/Crypto.unity.cpp
+++ b/src/beast/beast/crypto/Crypto.unity.cpp
@@ -23,9 +23,5 @@
#include
#include
-#include
-#include
#include
-
-#include
diff --git a/src/beast/beast/crypto/UnsignedInteger.h b/src/beast/beast/crypto/UnsignedInteger.h
deleted file mode 100644
index de2adbfd4b..0000000000
--- a/src/beast/beast/crypto/UnsignedInteger.h
+++ /dev/null
@@ -1,294 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-#ifndef BEAST_CRYPTO_UNSIGNEDINTEGER_H_INCLUDED
-#define BEAST_CRYPTO_UNSIGNEDINTEGER_H_INCLUDED
-
-#include
-#include
-
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-
-namespace beast {
-
-/** Represents a set of bits of fixed size.
-
- The data is stored in "canonical" format which is network (big endian)
- byte order, most significant byte first.
-
- In this implementation the pointer to the beginning of the canonical format
- may not be aligned.
-*/
-template
-class UnsignedInteger
-{
-public:
- /** Constant for determining the number of bytes. */
- static std::size_t const size = Bytes;
-
- // The underlying integer type we use when converting to calculation format.
- typedef std::uint32_t IntCalcType;
-
- // The type of object resulting from a conversion to calculation format.
- typedef UnsignedIntegerCalc CalcType;
-
- // Standard container compatibility
- typedef std::uint8_t value_type;
- typedef value_type* iterator;
- typedef value_type const* const_iterator;
-
- /** 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.
- */
- typedef hardened_hash <> hasher;
-
- /** Determins if two UnsignedInteger objects are equal. */
- class equal
- {
- public:
- bool operator() (UnsignedInteger const& lhs, UnsignedInteger const& rhs) const
- {
- return lhs.compare (rhs) == 0;
- }
- };
-
- //--------------------------------------------------------------------------
-
- /** Construct the object.
- The values are uninitialized.
- */
- UnsignedInteger ()
- {
- }
-
- /** Construct a copy. */
- UnsignedInteger (UnsignedInteger const& other)
- {
- this->operator= (other);
- }
-
- /** Construct from a raw memory.
- The area pointed to by buffer must be at least Bytes in size,
- or else undefined behavior will result.
- */
- /** @{ */
- explicit UnsignedInteger (void const* buf)
- {
- m_values [0] = 0; // clear any pad bytes
- std::memcpy (begin(), buf, Bytes);
- }
-
- template
- UnsignedInteger (InputIt first, InputIt last)
- {
- m_values [0] = 0; // clear any pad bytes
- assert (std::distance (first, last) == size);
- std::copy (first, last, begin());
- }
- /** @} */
-
- /** Assign from another UnsignedInteger. */
- UnsignedInteger& operator= (UnsignedInteger const& other)
- {
- // Perform an aligned, all inclusive copy that includes padding.
- std::copy (other.m_values, other.m_values + CalcCount, m_values);
- return *this;
- }
-
- /** Create from an integer type.
- @invariant IntegerType must be an unsigned integer type.
- */
- template
- static UnsignedInteger createFromInteger (UnsignedIntegralType value)
- {
- static_assert (Bytes >= sizeof (UnsignedIntegralType),
- "Bytes is too small.");
- UnsignedInteger result;
- value = toNetworkByteOrder (value);
- result.clear ();
- std::memcpy (result.end () - sizeof (value), &value,
- std::min (Bytes, sizeof (value)));
- return result;
- }
-
- /** Construct with a filled value. */
- static UnsignedInteger createFilled (value_type value)
- {
- UnsignedInteger result;
- result.fill (value);
- return result;
- }
-
- /** Fill with a particular byte value. */
- void fill (value_type value)
- {
- IntCalcType c;
- memset (&c, value, sizeof (c));
- std::fill (m_values, m_values + CalcCount, c);
- }
-
- /** Clear the contents to zero. */
- void clear ()
- {
- std::fill (m_values, m_values + CalcCount, 0);
- }
-
- /** Convert to calculation format. */
- CalcType toCalcType (bool convert = true)
- {
- return CalcType::fromCanonical (m_values, Bytes, convert);
- }
-
- /** Determine if all bits are zero. */
- bool isZero () const
- {
- for (int i = 0; i < CalcCount; ++i)
- {
- if (m_values [i] != 0)
- return false;
- }
-
- return true;
- }
-
- /** Determine if any bit is non-zero. */
- bool isNotZero () const
- {
- return ! isZero ();
- }
-
- /** Support conversion to `bool`.
- @return `true` if any bit is non-zero.
- */
- explicit
- operator bool() const
- {
- return isNotZero ();
- }
-
- /** Get an iterator to the beginning. */
- iterator begin ()
- {
- return get();
- }
-
- /** Get an iterator to past-the-end. */
- iterator end ()
- {
- return get()+Bytes;
- }
-
- /** Get a const iterator to the beginning. */
- const_iterator begin () const
- {
- return get();
- }
-
- /** Get a const iterator to past-the-end. */
- const_iterator end () const
- {
- return get()+Bytes;
- }
-
- /** Get a const iterator to the beginning. */
- const_iterator cbegin () const
- {
- return get();
- }
-
- /** Get a const iterator to past-the-end. */
- const_iterator cend () const
- {
- return get()+Bytes;
- }
-
- /** Compare two objects of equal size.
- The comparison is performed using a numeric lexicographical comparison.
- */
- int compare (UnsignedInteger const& other) const
- {
- return memcmp (cbegin (), other.cbegin (), Bytes);
- }
-
- /** Determine equality. */
- bool operator== (UnsignedInteger const& other) const
- {
- return compare (other) == 0;
- }
-
- /** Determine inequality. */
- bool operator!= (UnsignedInteger const& other) const
- {
- return compare (other) != 0;
- }
-
- /** Ordered comparison. */
- bool operator< (UnsignedInteger const& other) const
- {
- return compare (other) < 0;
- }
-
- /** Ordered comparison. */
- bool operator<= (UnsignedInteger const& other) const
- {
- return compare (other) <= 0;
- }
-
- /** Ordered comparison. */
- bool operator> (UnsignedInteger const& other) const
- {
- return compare (other) > 0;
- }
-
- /** Ordered comparison. */
- bool operator>= (UnsignedInteger const& other) const
- {
- return compare (other) >= 0;
- }
-
-private:
- static std::size_t const CalcCount = (Bytes + sizeof (IntCalcType) - 1) / sizeof (IntCalcType);
-
- value_type* get ()
- {
- return (reinterpret_cast (&m_values [0])) +
- ((sizeof(IntCalcType)-(Bytes&(sizeof(IntCalcType)-1)))&(sizeof(IntCalcType)-1));
- }
-
- value_type const* get () const
- {
- return (reinterpret_cast (&m_values [0])) +
- ((sizeof(IntCalcType)-(Bytes&(sizeof(IntCalcType)-1)))&(sizeof(IntCalcType)-1));
- }
-
- IntCalcType m_values [CalcCount];
-};
-
-}
-
-#endif
diff --git a/src/beast/beast/crypto/UnsignedIntegerCalc.h b/src/beast/beast/crypto/UnsignedIntegerCalc.h
deleted file mode 100644
index 53c88381bc..0000000000
--- a/src/beast/beast/crypto/UnsignedIntegerCalc.h
+++ /dev/null
@@ -1,442 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-#ifndef BEAST_CRYPTO_UNSIGNEDINTEGERCALC_H_INCLUDED
-#define BEAST_CRYPTO_UNSIGNEDINTEGERCALC_H_INCLUDED
-
-#include
-
-#include
-#include
-#include
-#include
-#include
-
-namespace beast {
-
-namespace detail {
-
-template
-struct DoubleWidthUInt;
-
-template <>
-struct DoubleWidthUInt
-{
- typedef std::uint32_t type;
-};
-
-template <>
-struct DoubleWidthUInt
-{
- typedef std::uint64_t type;
-};
-
-}
-
-/** Multiprecision unsigned integer suitable for calculations.
-
- The data is stored in "calculation" format, which means it can be
- readily used for performing calculations, but no raw access to the
- bytes are provided. To transmit a serialized unsigned integer or
- perform base encodings, it must be converted back into UnsignedInteger.
- The number is represented as a series of native UInt unsigned integer
- types, in order of increasing significance.
-
- This is a lightweight object, storage and ownership of the underlying
- data buffer is an external responsibility. The makes the class cheap to
- copy and pass by value.
-
- A consequence of this ownership model is that arithmetics operators
- which return results by value cannot be included in the interface.
-*/
-template
-class UnsignedIntegerCalc
-{
-public:
- typedef typename detail::DoubleWidthUInt ::type UIntBig;
-
- typedef std::size_t size_type;
-
- static UInt const maxUInt = ((UInt)(-1));
- static size_type const numBits = (sizeof(UInt)*8);
-
- //--------------------------------------------------------------------------
-
- /** Construct an empty integer / zero bits. */
- UnsignedIntegerCalc ()
- : m_size (0)
- , m_values (nullptr)
- {
- }
-
- /** Construct a reference to an existing buffer. */
- UnsignedIntegerCalc (UnsignedIntegerCalc const& other)
- : m_size (other.m_size)
- , m_values (other.m_values)
- {
- }
-
- /** Construct from an existing array of values.
- The existing data must already be in the "calculation" format.
- */
- UnsignedIntegerCalc (size_type count, UInt* values)
- : m_size (count)
- , m_values (values)
- {
- }
-
- /** Convert to calculation format from canonical format.
- This overwrites the callers memory without transferring ownership.
- Canonical format is defined as a big endian byte oriented
- multiprecision integer format. The buffer should point to the
- beginning of the storage area and not the beginning of the canonical
- data. Bytes is the desired canonical bytes.
- */
- static UnsignedIntegerCalc fromCanonical (
- void* buffer, size_type const bytes, bool swizzle = true)
- {
- UInt* const values (reinterpret_cast (buffer));
- size_type const count ((bytes + sizeof (UInt) - 1) / sizeof (UInt));
- if (swizzle)
- {
- // Zero fill the possibly uninitialized pad bytes
- std::memset (buffer, 0,
- ((sizeof(UInt)-(bytes&(sizeof(UInt)-1)))&(sizeof(UInt)-1)));
- // Swap and swizzle
- UInt* lo (values);
- UInt* hi (values + count - 1);
- while (lo < hi)
- {
- std::swap (*lo, *hi);
- *lo = fromNetworkByteOrder (*lo);
- ++lo;
- *hi = fromNetworkByteOrder (*hi);
- ++hi;
- }
- if (lo == hi)
- *lo = fromNetworkByteOrder (*lo);
- }
- return UnsignedIntegerCalc (count, values);
- }
-
- /** Convert the buffer back into canonical format.
- Since ownership was never transferred, the caller's data is
- restored to its original format. Typically this will be done
- as the last step of a series of operations.
- */
- void toCanonical ()
- {
- // Swap and swizzle
- UInt* lo (m_values);
- UInt* hi (m_values + m_size - 1);
- while (lo < hi)
- {
- std::swap (*lo, *hi);
- *lo = toNetworkByteOrder (*lo); ++lo;
- *hi = toNetworkByteOrder (*hi); --hi;
- }
- if (lo == hi)
- *lo = toNetworkByteOrder (*lo);
- }
-
- /** Assign a value from another integer.
- @note This does not transfer the reference to the buffer, it
- copies the values from one buffer to the other.
- */
- UnsignedIntegerCalc& operator= (UnsignedIntegerCalc const& other)
- {
- assert (other.size() <= size());
- size_type n (size());
- UInt* dest (m_values + size());
- for (; n-- > other.size();)
- *--dest = 0;
- UInt const* rhs (other.m_values + n);
- for (; n--;)
- *--dest = *--rhs;
- return *this;
- }
-
- /** Returns `true` if this represents the number zero. */
- bool isZero () const
- {
- for (size_type n (size()); n--;)
- if (m_values [n] != 0)
- return false;
- return true;
- }
-
- /** Returns `true` if this represents any number other than zero. */
- bool isNotZero () const
- {
- return ! isZero ();
- }
-
- /** Safe conversion to `bool`, `true` means a non-zero value. */
- explicit
- operator bool() const
- {
- return isNotZero ();
- }
-
- /** Returns `true` if the buffer has 0 values. */
- bool empty () const
- {
- return m_size == 0;
- }
-
- /** Returns the size of the buffer, in values. */
- size_type size () const
- {
- return m_size;
- }
-
- /** Safe array indexing to arbitrary positions.
- If the index is out of range, zero is returned.
- */
- UInt operator[] (size_type n) const
- {
- if (n >= 0 && n < size())
- return m_values [n];
- return 0;
- }
-
- /** Universal comparison.
- The comparison is performed numerically.
- The return values have the same meaning as memcmp().
- */
- int compare (UnsignedIntegerCalc const& other) const
- {
- if (size() == 0)
- {
- if (other.size() == 0)
- return 0;
- return -1;
- }
- else if (other.size() == 0)
- {
- return 1;
- }
-
- for (size_type n (std::max (size(), other.size())); n--;)
- {
- UInt lhs ((*this)[n]);
- UInt rhs (other[n]);
- if (lhs < rhs)
- return -1;
- else if (lhs > rhs)
- return 1;
- }
-
- return 0;
- }
-
- /** Determine equality. */
- bool operator== (UnsignedIntegerCalc const& other) const
- {
- return compare (other) == 0;
- }
-
- /** Determine inequality. */
- bool operator!= (UnsignedIntegerCalc const& other) const
- {
- return compare (other) != 0;
- }
-
- /** Ordered comparison. */
- bool operator< (UnsignedIntegerCalc const& other) const
- {
- return compare (other) < 0;
- }
-
- /** Ordered comparison. */
- bool operator<= (UnsignedIntegerCalc const& other) const
- {
- return compare (other) <= 0;
- }
-
- /** Ordered comparison. */
- bool operator> (UnsignedIntegerCalc const& other) const
- {
- return compare (other) > 0;
- }
-
- /** Ordered comparison. */
- bool operator>= (UnsignedIntegerCalc const& other) const
- {
- return compare (other) >= 0;
- }
-
- /** Assign zero. */
- void clear ()
- {
- UInt* dest (m_values - 1);
- for (size_type n (size()); n--;)
- *++dest = 0;
- }
-
- /** Perform bitwise logical-not. */
- /*
- UnsignedIntegerCalc& not ()
- {
- unaryAssign (Not());
- return *this;
- }
- */
-
- /** Perform bitwise logical-or. */
- UnsignedIntegerCalc& operator|= (UnsignedIntegerCalc const& rhs)
- {
- binaryAssign (rhs, Or());
- return *this;
- }
-
- /** Perform bitwise logical-and. */
- UnsignedIntegerCalc& operator&= (UnsignedIntegerCalc const& rhs)
- {
- binaryAssign (rhs, And());
- return *this;
- }
-
- /** Perform bitwise logical-xor. */
- UnsignedIntegerCalc& operator^= (UnsignedIntegerCalc const& rhs)
- {
- binaryAssign (rhs, Xor());
- return *this;
- }
-
- /** Perform addition. */
- UnsignedIntegerCalc& operator+= (UnsignedIntegerCalc const& v)
- {
- UIntBig carry (0);
- UInt* lhs (m_values);
- UInt const* rhs (v.m_values - 1);
- for (size_type n (0); n maxUInt)
- {
- part &= maxUInt;
- carry = 1;
- }
- *lhs++ = UInt (part);
- }
- assert (carry == 0); // overflow
- return *this;
- }
-
- /** Perform small addition. */
- UnsignedIntegerCalc& operator+= (UInt rhs)
- {
- UnsignedIntegerCalc const v (1, &rhs);
- return operator+= (v);
- }
-
- /** Perform small multiply. */
- UnsignedIntegerCalc& operator*= (UInt rhs)
- {
- UIntBig carry (0);
- UInt* lhs (m_values - 1);
- for (size_type n (size()); n--;)
- {
- UIntBig part (carry);
- carry = 0;
- part += (*++lhs) * UIntBig(rhs);
- carry = part >> numBits;
- *lhs = UInt (part & maxUInt);
- }
- assert (carry == 0); // overflow
- return *this;
- }
-
- /** Small division. */
- UnsignedIntegerCalc operator/= (UInt rhs)
- {
- UIntBig dividend (0);
- UInt* lhs (m_values+size());
- for (size_type n (size()); n--;)
- {
- dividend |= *--lhs;
- *lhs = UInt (dividend / rhs);
- dividend = (dividend % rhs) << numBits;
- }
- return *this;
- }
-
- /** Small modulus. */
- UInt operator% (UInt rhs) const
- {
- UIntBig modsq = 1;
- UIntBig result = 0;
- UInt const* lhs (m_values);
- for (size_type n (size()); n--; ++lhs)
- {
- for (int bit (0); bit < numBits; ++bit)
- {
- if (((*lhs) & (1 << bit)) != 0)
- {
- result += modsq;
- if (result >= rhs)
- result -= rhs;
- }
- modsq <<= 1;
- if (modsq >= rhs)
- modsq -= rhs;
- }
- }
- return UInt (result);
- }
-
-private:
- struct Not { void operator() (UInt& rv) const { rv = ~rv; } };
- struct Or { void operator() (UInt& lhs, UInt rhs) const { lhs |= rhs; } };
- struct And { void operator() (UInt& lhs, UInt rhs) const { lhs &= rhs; } };
- struct Xor { void operator() (UInt& lhs, UInt rhs) const { lhs ^= rhs; } };
-
- template
- void unaryAssign (Operator op = Operator())
- {
- UInt* dest (m_values-1);
- for (size_type n (size()); n--;)
- op (*++dest);
- }
-
- template
- void binaryAssign (UnsignedIntegerCalc const& other, Operator op = Operator ())
- {
- UInt* dest (m_values + size());
- size_type n (size());
- for (; n-- > other.size();)
- *--dest = 0;
- UInt const* rhs (other.m_values + n);
- for (UInt const* rhs (other.m_values + n); n--;)
- op (*--dest, *--rhs);
- }
-
- size_type m_size;
- UInt* m_values;
-};
-
-}
-
-#endif
diff --git a/src/beast/beast/crypto/impl/UnsignedInteger.cpp b/src/beast/beast/crypto/impl/UnsignedInteger.cpp
deleted file mode 100644
index a9447f2a5b..0000000000
--- a/src/beast/beast/crypto/impl/UnsignedInteger.cpp
+++ /dev/null
@@ -1,346 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Portions are Copyright (c) 2013 the authors listed at the following URL,
- and/or the authors of referenced articles or incorporated external code:
- http://en.literateprograms.org/Arbitrary-precision_integer_arithmetic_(C)
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-#include
-
-#include
-
-namespace beast {
-
-namespace multiprecsion {
-
-#if 0
-
-/* Copyright (c) 2013 the authors listed at the following URL, and/or
- the authors of referenced articles or incorporated external code:
- http://en.literateprograms.org/Arbitrary-precision_integer_arithmetic_(C)
-
- Permission is hereby granted, free of charge, to any person obtaining
- a copy of this software and associated documentation files (the
- "Software"), to deal in the Software without restriction, including
- without limitation the rights to use, copy, modify, merge, publish,
- distribute, sublicense, and/or sell copies of the Software, and to
- permit persons to whom the Software is furnished to do so, subject to
- the following conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-*/
-
-//
-// Retrieved from: http://en.literateprograms.org/Arbitrary-precision_integer_arithmetic_(C)?oldid=16902
-//
-
-typedef unsigned short component_t;
-typedef unsigned long double_component_t;
-
-#define MAX_COMPONENT ((component_t)(-1))
-#define COMPONENT_BITS (sizeof(component_t)*CHAR_BIT)
-
-#define LOG_2_10 3.3219280948873623478703194294894
-
-#define MIN(x,y) ((x)<(y) ? (x) : (y))
-#define MAX(x,y) ((x)>(y) ? (x) : (y))
-
-typedef struct {
- component_t* c; /* least-significant word first */
- int num_components;
-} integer;
-
-
-integer create_integer(int components);
-void free_integer(integer i);
-void set_zero_integer(integer i);
-void copy_integer(integer source, integer target);
-void add_integer(integer left, integer right, integer result);
-void subtract_integer(integer left, integer right, integer result);
-void multiply_small_integer(integer left, component_t right, integer result);
-void multiply_integer(integer left, integer right, integer result);
-int compare_integers(integer left, integer right);
-void shift_left_one_integer(integer arg);
-void shift_right_one_integer(integer arg);
-component_t mod_small_integer(integer left, component_t right);
-void mod_integer(integer left, integer right, integer result);
-void divide_small_integer(integer left, component_t right, integer result);
-integer string_to_integer(char* s);
-char* integer_to_string(integer x);
-int is_zero_integer(integer x);
-
-//------------------------------------------------------------------------------
-
-integer create_integer(int components) {
- integer result;
- result.num_components = components;
- result.c = (component_t*)malloc(sizeof(component_t)*components);
- return result;
-}
-
-
-void free_integer(integer i) {
- free(i.c);
-}
-
-
-void set_zero_integer(integer i) {
- memset(i.c, 0, sizeof(component_t)*i.num_components);
-}
-
-
-int is_zero_integer(integer x) {
- int i;
- for(i=0; i < x.num_components; i++) {
- if (x.c[i] != 0) return 0;
- }
- return 1;
-}
-
-void copy_integer(integer source, integer target) {
- memmove(target.c, source.c,
- sizeof(component_t)*MIN(source.num_components, target.num_components));
- if (target.num_components > source.num_components) {
- memset(target.c + source.num_components, 0,
- sizeof(component_t)*(target.num_components - source.num_components));
- }
-}
-
-void add_integer(integer left, integer right, integer result) {
- double_component_t carry = 0;
- int i;
- for(i=0; i MAX_COMPONENT) {
- partial_sum &= MAX_COMPONENT;
- carry = 1;
- }
- result.c[i] = (component_t)partial_sum;
- }
- for ( ; i < result.num_components; i++) { result.c[i] = 0; }
-}
-
-void subtract_integer(integer left, integer right, integer result) {
- int borrow = 0;
- int i;
- for(i=0; i> COMPONENT_BITS;
- result.c[i] = (component_t)(partial_sum & MAX_COMPONENT);
- }
- for ( ; i < result.num_components; i++) { result.c[i] = 0; }
-}
-
-void multiply_integer(integer left, integer right, integer result) {
- int i, lidx, ridx;
- double_component_t carry = 0;
- int max_size_no_carry;
- int left_max_component = left.num_components - 1;
- int right_max_component = right.num_components - 1;
- while(left.c[left_max_component] == 0) left_max_component--;
- while(right.c[right_max_component] == 0) right_max_component--;
- max_size_no_carry = left_max_component + right_max_component;
- for(i=0; i <= max_size_no_carry || carry != 0; i++) {
- double_component_t partial_sum = carry;
- carry = 0;
- lidx = MIN(i, left_max_component);
- ridx = i - lidx;
- while(lidx >= 0 && ridx <= right_max_component) {
- partial_sum += ((double_component_t)left.c[lidx])*right.c[ridx];
- carry += partial_sum >> COMPONENT_BITS;
- partial_sum &= MAX_COMPONENT;
- lidx--; ridx++;
- }
- result.c[i] = partial_sum;
- }
- for ( ; i < result.num_components; i++) { result.c[i] = 0; }
-}
-
-int compare_integers(integer left, integer right) {
- int i = MAX(left.num_components - 1, right.num_components - 1);
- for ( ; i >= 0; i--) {
- component_t left_comp =
- (i < left.num_components) ? left.c[i] : 0;
- component_t right_comp =
- (i < right.num_components) ? right.c[i] : 0;
- if (left_comp < right_comp)
- return -1;
- else if (left_comp > right_comp)
- return 1;
- }
- return 0;
-}
-
-void shift_left_one_integer(integer arg) {
- int i;
- arg.c[arg.num_components - 1] <<= 1;
- for (i = arg.num_components - 2; i >= 0; i--) {
- arg.c[i + 1] |= arg.c[i] >> (COMPONENT_BITS - 1);
- arg.c[i] <<= 1;
- }
-}
-
-void shift_right_one_integer(integer arg) {
- int i;
- arg.c[0] >>= 1;
- for (i = 1; i < arg.num_components; i++) {
- arg.c[i - 1] |= (arg.c[i] & 1) << (COMPONENT_BITS - 1);
- arg.c[i] >>= 1;
- }
-}
-
-component_t mod_small_integer(integer left, component_t right) {
- double_component_t mod_two_power = 1;
- double_component_t result = 0;
- int i, bit;
- for(i=0; i= right) {
- result -= right;
- }
- }
- mod_two_power <<= 1;
- if (mod_two_power >= right) {
- mod_two_power -= right;
- }
- }
- }
- return (component_t)result;
-}
-
-void mod_integer(integer left, integer right, integer result) {
- integer mod_two_power = create_integer(right.num_components + 1);
- int i, bit;
- set_zero_integer(result);
- set_zero_integer(mod_two_power);
- mod_two_power.c[0] = 1;
- for(i=0; i= 0) {
- subtract_integer(result, right, result);
- }
- }
- shift_left_one_integer(mod_two_power);
- if (compare_integers(mod_two_power, right) >= 0) {
- subtract_integer(mod_two_power, right, mod_two_power);
- }
- }
- }
- free_integer(mod_two_power);
-}
-
-void divide_small_integer(integer left, component_t right, integer result) {
- double_component_t dividend = 0;
- int i;
- for (i = left.num_components - 1; i >= 0; i--) {
- dividend |= left.c[i];
- result.c[i] = dividend/right;
- dividend = (dividend % right) << COMPONENT_BITS;
- }
-}
-
-integer string_to_integer(char* s) {
- integer result = create_integer((int)ceil(LOG_2_10*strlen(s)/COMPONENT_BITS));
- set_zero_integer(result);
- integer digit = create_integer(1);
- int i;
- for (i = 0; s[i] != '\0'; i++) {
- multiply_small_integer(result, 10, result);
- digit.c[0] = s[i] - '0';
- add_integer(result, digit, result);
- }
- free_integer(digit);
- return result;
-}
-
-
-char* integer_to_string(integer x) {
- int i, result_len;
- char* result =
- (char*)malloc((int)ceil(COMPONENT_BITS*x.num_components/LOG_2_10) + 2);
- integer ten = create_integer(1);
- ten.c[0] = 10;
-
- if (is_zero_integer(x)) {
- strcpy(result, "0");
- } else {
- for (i = 0; !is_zero_integer(x); i++) {
- result[i] = (char)mod_small_integer(x, 10) + '0';
- divide_small_integer(x, 10, x);
- }
- result[i] = '\0';
- }
-
- result_len = strlen(result);
- for(i=0; i < result_len/2; i++) {
- char temp = result[i];
- result[i] = result[result_len - i - 1];
- result[result_len - i - 1] = temp;
- }
-
- free_integer(ten);
- return result;
-}
-
-#endif
-
-}
-
-}
diff --git a/src/beast/beast/crypto/tests/BinaryEncoding.cpp b/src/beast/beast/crypto/tests/BinaryEncoding.cpp
deleted file mode 100644
index af85c98df4..0000000000
--- a/src/beast/beast/crypto/tests/BinaryEncoding.cpp
+++ /dev/null
@@ -1,417 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-// MODULES: ../../../modules/beast_core/beast_core.beast_core.unity.cpp ../../strings/Strings.cpp ../../chrono/Chrono.cpp ../../threads/Threads.cpp
-#include
-#include
-
-#include
-#include
-
-#include
-#include
-
-namespace beast {
-
-/** Generic algorithms for base encoding and decoding. */
-class BinaryEncoding
-{
-public:
- /** Concept: Conversion
-
- X denotes a Conversion class, a is a value of type X,
- i is an integral type.
-
- Requirements:
-
- Expression Type Notes/Contracts
- ------------- ----------- ------------------
- X a;
- X::radix size_type constexpr
- a.map (i) char maps base numeral to a char
- */
-
- /** Encode the unsigned integer into a string using the specified conversion. */
- template
- static std::string encode (UnsignedInteger v, Conversion c = Conversion ())
- {
- // bi is destroyed in this process
- typename UnsignedInteger ::CalcType bi (v.toCalcType ());
- std::size_t const radix (Conversion::radix);
- std::string s;
- s.reserve (bi.size() * 3); // guess
- while (bi.isNotZero ())
- {
- std::size_t const m (bi % radix);
- bi /= radix;
- s.push_back (c.map (m));
- }
- std::reverse (s.begin(), s.end());
- return s;
- }
-
- /** Decode the string into an unsigned integer.
- The size must match exactly
- @return `true` on success.
- */
- template
- static bool decode (UnsignedInteger & rv,
- std::string const& s, Conversion c = Conversion ())
- {
- typename UnsignedInteger ::CalcType bi (rv.toCalcType (false));
- std::size_t const radix (Conversion::radix);
- bi.clear ();
- for (std::string::const_iterator iter (s.begin()); iter != s.end(); ++iter)
- {
- int const v (c.invert (*iter));
- if (v == -1)
- return false;
- bi *= radix;
- bi += v;
- }
- bi.toCanonical();
- return true;
- }
-};
-
-//------------------------------------------------------------------------------
-
-// Some common code
-template
-class BaseConversion
-{
-public:
- char map (std::size_t i) const
- {
- return Conversion::alphabet () [i];
- }
-
- int invert (char c) const
- {
- return Conversion::inverse_alphabet () [c];
- }
-
- static std::vector const& inverse_alphabet ()
- {
- static std::vector t (invert (Conversion::alphabet(), Conversion::radix));
- return t;
- }
-
- /** Build the inverse mapping table from characters to digits. */
- static std::vector
- invert (std::string const& alphabet, int radix)
- {
- std::vector table (256, -1);
- for (int i (0); i < radix; ++i)
- table [alphabet [i]] = i;
- return table;
- }
-
-};
-
-//------------------------------------------------------------------------------
-
-/** Foolproof hexadecimal encoding and decoding facility.
- This is to check the correctness of the more complex converters.
-*/
-class HexEncoding
-{
-public:
- template
- static std::string encode (UnsignedInteger const& v)
- {
- std::string s;
- 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--;)
- {
- std::uint8_t const v (*++src);
- s.push_back (tab [v>>4]);
- s.push_back (tab [v&0x0f]);
- }
- return s;
- }
-
- template
- static bool decode (UnsignedInteger & rv,
- std::string const& s)
- {
- // can't have an odd size
- if (s.size() & 1)
- return false;
- 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();)
- {
- int const n1 (tab [*iter++]);
- if (n1 == -1)
- return false;
- int const n2 (tab [*iter++]);
- if (n2 == -1)
- return false;
- *++dest = ((std::uint8_t)((n1<<4)|n2));
- }
- return true;
- }
-
- static std::string const& alphabet ()
- {
- static std::string s ("0123456789ABCDEF");
- return s;
- }
-
- static std::vector const& inverse_alphabet ()
- {
- static std::vector s (invert (alphabet(), 16));
- return s;
- }
-
- /** Build the inverse mapping table from characters to digits. */
- static std::vector
- invert (std::string const& alphabet, int radix)
- {
- std::vector table (256, -1);
- for (int i (0); i < radix; ++i)
- table [alphabet [i]] = int(i);
- return table;
- }
-};
-
-//------------------------------------------------------------------------------
-
-/** Base58 conversion used by Bitcoin. */
-class BitcoinBase58Conversion : public BaseConversion
-{
-public:
- static std::size_t const radix = 58;
-
- char const* name () const
- {
- return "BitcoinBase58";
- }
-
- static std::string const& alphabet ()
- {
- static std::string s (
- "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
- );
- return s;
- }
-};
-
-//------------------------------------------------------------------------------
-
-/** Base58 conversion used by Ripple. */
-class RippleBase58Conversion : public BaseConversion
-{
-public:
- static std::size_t const radix = 58;
-
- char const* name () const
- {
- return "RippleBase58";
- }
-
- static std::string const& alphabet ()
- {
- static std::string s (
- "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"
- );
- return s;
- }
-};
-
-//------------------------------------------------------------------------------
-
-class Base64Conversion : public BaseConversion
-{
-public:
- static std::size_t const radix = 64;
-
- char const* name () const
- {
- return "Base64";
- }
-
- static std::string const& alphabet ()
- {
- static std::string s (
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
- );
- return s;
- }
-};
-
-//------------------------------------------------------------------------------
-
-class Base16Conversion : public BaseConversion
-{
-public:
- static std::size_t const radix = 16;
-
- char const* name () const
- {
- return "Hex";
- }
-
- static std::string const& alphabet ()
- {
- static std::string s (
- "0123456789ABCDEF"
- );
- return s;
- }
-};
-
-//------------------------------------------------------------------------------
-
-class BinaryEncoding_test : public unit_test::suite
-{
-public:
- // This is a baseline for the other tests
- template
- void testBase16 ()
- {
- Random r;
- testcase ("base16");
- for (int i = 0; i < 50; ++i)
- {
- typedef UnsignedInteger UInt;
- UInt v0;
- r.fillBitsRandomly (v0.begin(), UInt::size);
- std::string const good (HexEncoding::encode (v0));
-
- UInt v1;
- bool const success (HexEncoding::decode (v1, good));
- if (expect (success))
- {
- expect (v0 == v1);
-
- Base16Conversion c;
- std::string const check (BinaryEncoding::encode (v0, c));
- expect (good == check,
- std::string ("expected ") + good + " but got " + check);
- }
- }
- }
-
- template
- void testBase64Bytes (
- std::string const& vin, std::string const& vout,
- Base64Conversion c = Base64Conversion ())
- {
- typedef UnsignedInteger UInt;
- UInt v1 (vin.c_str());
- std::string const s1 (BinaryEncoding::encode (v1, c));
- log <<
- vout + " to " + s1;
- expect (vout == s1);
-
- UInt v2;
- bool const success (BinaryEncoding::decode (v2, vout, c));
- if (expect (success))
- {
- std::string const s2 (BinaryEncoding::encode (v2, c));
- log <<
- vin + " to " + s2;
- }
- }
-
- void testBase64 ()
- {
- testcase ("Base64");
-
- // input (uint)
- std::string const vin [] = {
- "","f","fo","foo","foob","fooba","foobar"
- };
-
- // output (encoded string)
- std::string const vout [] = {
- "","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"
- };
-
- //testBase64Bytes <0> (vin [0], vout [0]);
- testBase64Bytes <1> (vin [1], vout [1]);
- testBase64Bytes <2> (vin [2], vout [2]);
- testBase64Bytes <3> (vin [3], vout [3]);
- testBase64Bytes <4> (vin [4], vout [4]);
- testBase64Bytes <5> (vin [5], vout [5]);
- testBase64Bytes <6> (vin [6], vout [6]);
- }
-
- template
- void testEncode (Conversion c = Conversion())
- {
- typedef UnsignedInteger UInt;
-
-#if 0
- std::stringstream ss;
- ss <<
- c.name() << " <" << Bytes << ">";
- testcase (ss.str());
-#else
- testcase << c.name() << " <" << Bytes << ">";
-#endif
-
- Random r;
- for (int i = 0; i < 50; ++i)
- {
- UInt v1;
- r.fillBitsRandomly (v1.begin(), UInt::size);
- std::string const s1 (BinaryEncoding::encode (v1, c));
-
- UInt v2;
- bool success (BinaryEncoding::decode (v2, s1, c));
- if (expect (success))
- expect (v1 == v2);
- }
- }
-
- void run ()
- {
- testBase16 <10> ();
-
-#if 0
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
-
- testBase64 ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
- testEncode ();
-#endif
- }
-};
-
-BEAST_DEFINE_TESTSUITE_MANUAL(BinaryEncoding,crypto,beast);
-
-}
diff --git a/src/beast/beast/crypto/tests/UnsignedInteger.test.cpp b/src/beast/beast/crypto/tests/UnsignedInteger.test.cpp
deleted file mode 100644
index 173b8892d0..0000000000
--- a/src/beast/beast/crypto/tests/UnsignedInteger.test.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Portions are Copyright (c) 2013 the authors listed at the following URL,
- and/or the authors of referenced articles or incorporated external code:
- http://en.literateprograms.org/Arbitrary-precision_integer_arithmetic_(C)
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-#include
-
-#include
-
-namespace beast {
-
-class UnsignedInteger_test : public unit_test::suite
-{
-public:
- template
- void test ()
- {
- typedef UnsignedInteger UInt;
-
- std::stringstream ss;
- ss <<
- "bytes=" << Bytes;
- testcase (ss.str());
-
- UInt zero;
- zero.fill (0);
- expect (zero.isZero (), "should be zero");
- expect (! zero.isNotZero (), "sould not be non-zero");
-
- UInt one (UInt::createFromInteger (1U));
- expect (one == UInt::createFromInteger (1U), "should be equal");
-
- expect (! one.isZero (), "should not be zero");
- expect (one.isNotZero (), "sould be non-zero");
-
- expect (zero < one, "should be less");
- expect (one > zero, "should be greater");
- expect (zero >= zero, "should be less than or equal");
- expect (one <= one, "should be less than or equal");
-
- expect (zero == zero, "should be equal");
- expect (zero != one, "should not be equal");
-
- expect (zero == UInt::createFromInteger (0U), "should be zero");
- expect (one == UInt::createFromInteger (1U), "should be one");
- expect (one != UInt::createFromInteger (2U), "should not be two");
-
- UInt largest = UInt::createFilled (0xff);
-
- expect (largest > zero && largest > one, "should be greater");
- }
-
- void run()
- {
- test <16> ();
- test <33> ();
- }
-
-private:
-};
-
-BEAST_DEFINE_TESTSUITE(UnsignedInteger,crypto,beast);
-
-}
diff --git a/src/beast/beast/insight/impl/StatsDCollector.cpp b/src/beast/beast/insight/impl/StatsDCollector.cpp
index cc93689e95..742f60c159 100644
--- a/src/beast/beast/insight/impl/StatsDCollector.cpp
+++ b/src/beast/beast/insight/impl/StatsDCollector.cpp
@@ -347,7 +347,7 @@ public:
ss << s;
}
//m_journal.trace << std::endl << ss.str ();
- Logger::outputDebugString (ss.str ());
+ outputDebugString (ss.str ());
#endif
}
diff --git a/src/beast/beast/intrusive/LockFreeStack.h b/src/beast/beast/intrusive/LockFreeStack.h
index 34fa85ccb7..92d9201fe2 100644
--- a/src/beast/beast/intrusive/LockFreeStack.h
+++ b/src/beast/beast/intrusive/LockFreeStack.h
@@ -20,8 +20,7 @@
#ifndef BEAST_INTRUSIVE_LOCKFREESTACK_H_INCLUDED
#define BEAST_INTRUSIVE_LOCKFREESTACK_H_INCLUDED
-#include
-
+#include
#include
#include
@@ -80,7 +79,7 @@ public:
LockFreeStackIterator& operator++ ()
{
- m_node = m_node->m_next.get();
+ m_node = m_node->m_next.load ();
return static_cast (*this);
}
@@ -147,22 +146,24 @@ public:
class Node
{
public:
- Node () = default;
+ Node ()
+ : m_next (nullptr)
+ { }
+
+ explicit Node (Node* next)
+ : m_next (next)
+ { }
Node(Node const&) = delete;
Node& operator= (Node const&) = delete;
- explicit Node (Node* next) : m_next (next)
- {
- }
-
private:
friend class LockFreeStack;
template
friend class LockFreeStackIterator;
- Atomic m_next;
+ std::atomic m_next;
};
public:
@@ -190,7 +191,7 @@ public:
/** Returns true if the stack is empty. */
bool empty() const
{
- return m_head.get() == &m_end;
+ return m_head.load () == &m_end;
}
/** Push a node onto the stack.
@@ -208,14 +209,15 @@ public:
bool push_front (Node* node)
{
bool first;
- Node* head;
+ Node* old_head = m_head.load (std::memory_order_relaxed);
do
{
- head = m_head.get ();
- first = head == &m_end;
- node->m_next = head;
+ first = (old_head == &m_end);
+ node->m_next = old_head;
}
- while (!m_head.compareAndSetBool (node, head));
+ while (!m_head.compare_exchange_strong (old_head, node,
+ std::memory_order_release,
+ std::memory_order_relaxed));
return first;
}
@@ -230,16 +232,17 @@ public:
*/
Element* pop_front ()
{
- Node* node;
- Node* head;
+ Node* node = m_head.load ();
+ Node* new_head;
do
{
- node = m_head.get ();
if (node == &m_end)
return nullptr;
- head = node->m_next.get ();
+ new_head = node->m_next.load ();
}
- while (!m_head.compareAndSetBool (head, node));
+ while (!m_head.compare_exchange_strong (node, new_head,
+ std::memory_order_release,
+ std::memory_order_relaxed));
return static_cast (node);
}
@@ -252,7 +255,7 @@ public:
/** @{ */
iterator begin ()
{
- return iterator (m_head.get ());
+ return iterator (m_head.load ());
}
iterator end ()
@@ -262,7 +265,7 @@ public:
const_iterator begin () const
{
- return const_iterator (m_head.get ());
+ return const_iterator (m_head.load ());
}
const_iterator end () const
@@ -272,7 +275,7 @@ public:
const_iterator cbegin () const
{
- return const_iterator (m_head.get ());
+ return const_iterator (m_head.load ());
}
const_iterator cend () const
@@ -283,7 +286,7 @@ public:
private:
Node m_end;
- Atomic m_head;
+ std::atomic m_head;
};
}
diff --git a/src/beast/beast/module/asio/AsyncObject.h b/src/beast/beast/module/asio/AsyncObject.h
index 9ba4b33e49..38d8e15fca 100644
--- a/src/beast/beast/module/asio/AsyncObject.h
+++ b/src/beast/beast/module/asio/AsyncObject.h
@@ -20,7 +20,7 @@
#ifndef BEAST_ASIO_ASYNCOBJECT_H_INCLUDED
#define BEAST_ASIO_ASYNCOBJECT_H_INCLUDED
-#include
+#include
#include
namespace beast {
@@ -33,11 +33,16 @@ namespace asio {
template
class AsyncObject
{
+protected:
+ AsyncObject ()
+ : m_pending (0)
+ { }
+
public:
~AsyncObject ()
{
// Destroying the object with I/O pending? Not a clean exit!
- assert (m_pending.get() == 0);
+ assert (m_pending.load () == 0);
}
/** RAII container that maintains the count of pending I/O.
@@ -65,8 +70,9 @@ public:
m_owner->asyncHandlersComplete ();
}
+ CompletionCounter& operator= (CompletionCounter const&) = delete;
+
private:
- CompletionCounter& operator= (CompletionCounter const&);
Derived* m_owner;
};
@@ -83,7 +89,7 @@ public:
private:
// The number of handlers pending.
- beast::Atomic m_pending;
+ std::atomic m_pending;
};
}
diff --git a/src/beast/beast/module/core/containers/Array.h b/src/beast/beast/module/core/containers/Array.h
index edcef0320f..6391e3821c 100644
--- a/src/beast/beast/module/core/containers/Array.h
+++ b/src/beast/beast/module/core/containers/Array.h
@@ -1050,8 +1050,8 @@ private:
void minimiseStorageAfterRemoval()
{
- if (data.numAllocated > bmax (minimumAllocatedSize, numUsed * 2))
- data.shrinkToNoMoreThan (bmax (numUsed, bmax (minimumAllocatedSize, 64 / (int) sizeof (ElementType))));
+ if (data.numAllocated > std::max (minimumAllocatedSize, numUsed * 2))
+ data.shrinkToNoMoreThan (std::max (numUsed, std::max (minimumAllocatedSize, 64 / (int) sizeof (ElementType))));
}
};
diff --git a/src/beast/beast/module/core/containers/LinkedListPointer.h b/src/beast/beast/module/core/containers/LinkedListPointer.h
deleted file mode 100644
index ea3bf557a7..0000000000
--- a/src/beast/beast/module/core/containers/LinkedListPointer.h
+++ /dev/null
@@ -1,371 +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_LINKEDLISTPOINTER_H_INCLUDED
-#define BEAST_LINKEDLISTPOINTER_H_INCLUDED
-
-namespace beast
-{
-
-//==============================================================================
-/**
- Helps to manipulate singly-linked lists of objects.
-
- For objects that are designed to contain a pointer to the subsequent item in the
- list, this class contains methods to deal with the list. To use it, the ObjectType
- class that it points to must contain a LinkedListPointer called nextListItem, e.g.
-
- @code
- struct MyObject
- {
- int x, y, z;
-
- // A linkable object must contain a member with this name and type, which must be
- // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
- // you could make your class a friend of a LinkedListPointer instead).
- LinkedListPointer nextListItem;
- };
-
- LinkedListPointer myList;
- myList.append (new MyObject());
- myList.append (new MyObject());
-
- int numItems = myList.size(); // returns 2
- MyObject* lastInList = myList.getLast();
- @endcode
-*/
-template
-class LinkedListPointer
-{
-public:
- //==============================================================================
- /** Creates a null pointer to an empty list. */
- LinkedListPointer() noexcept
- : item (nullptr)
- {
- }
-
- LinkedListPointer(LinkedListPointer const&) = delete;
- LinkedListPointer& operator= (LinkedListPointer const&) = delete;
-
- /** Creates a pointer to a list whose head is the item provided. */
- explicit LinkedListPointer (ObjectType* const headItem) noexcept
- : item (headItem)
- {
- }
-
- /** Sets this pointer to point to a new list. */
- LinkedListPointer& operator= (ObjectType* const newItem) noexcept
- {
- item = newItem;
- return *this;
- }
-
- #if BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS
- LinkedListPointer (LinkedListPointer&& other) noexcept
- : item (other.item)
- {
- other.item = nullptr;
- }
-
- LinkedListPointer& operator= (LinkedListPointer&& other) noexcept
- {
- bassert (this != &other); // hopefully the compiler should make this situation impossible!
-
- item = other.item;
- other.item = nullptr;
- return *this;
- }
- #endif
-
- //==============================================================================
- /** Returns the item which this pointer points to. */
- inline operator ObjectType*() const noexcept
- {
- return item;
- }
-
- /** Returns the item which this pointer points to. */
- inline ObjectType* get() const noexcept
- {
- return item;
- }
-
- /** Returns the last item in the list which this pointer points to.
- This will iterate the list and return the last item found. Obviously the speed
- of this operation will be proportional to the size of the list. If the list is
- empty the return value will be this object.
- If you're planning on appending a number of items to your list, it's much more
- efficient to use the Appender class than to repeatedly call getLast() to find the end.
- */
- LinkedListPointer& getLast() noexcept
- {
- LinkedListPointer* l = this;
-
- while (l->item != nullptr)
- l = &(l->item->nextListItem);
-
- return *l;
- }
-
- /** Returns the number of items in the list.
- Obviously with a simple linked list, getting the size involves iterating the list, so
- this can be a lengthy operation - be careful when using this method in your code.
- */
- int size() const noexcept
- {
- int total = 0;
-
- for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
- ++total;
-
- return total;
- }
-
- /** Returns the item at a given index in the list.
- Since the only way to find an item is to iterate the list, this operation can obviously
- be slow, depending on its size, so you should be careful when using this in algorithms.
- */
- LinkedListPointer& operator[] (int index) noexcept
- {
- LinkedListPointer* l = this;
-
- while (--index >= 0 && l->item != nullptr)
- l = &(l->item->nextListItem);
-
- return *l;
- }
-
- /** Returns the item at a given index in the list.
- Since the only way to find an item is to iterate the list, this operation can obviously
- be slow, depending on its size, so you should be careful when using this in algorithms.
- */
- const LinkedListPointer& operator[] (int index) const noexcept
- {
- const LinkedListPointer* l = this;
-
- while (--index >= 0 && l->item != nullptr)
- l = &(l->item->nextListItem);
-
- return *l;
- }
-
- /** Returns true if the list contains the given item. */
- bool contains (const ObjectType* const itemToLookFor) const noexcept
- {
- for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
- if (itemToLookFor == i)
- return true;
-
- return false;
- }
-
- //==============================================================================
- /** Inserts an item into the list, placing it before the item that this pointer
- currently points to.
- */
- void insertNext (ObjectType* const newItem)
- {
- bassert (newItem != nullptr);
- bassert (newItem->nextListItem == nullptr);
- newItem->nextListItem = item;
- item = newItem;
- }
-
- /** Inserts an item at a numeric index in the list.
- Obviously this will involve iterating the list to find the item at the given index,
- so be careful about the impact this may have on execution time.
- */
- void insertAtIndex (int index, ObjectType* newItem)
- {
- bassert (newItem != nullptr);
- LinkedListPointer* l = this;
-
- while (index != 0 && l->item != nullptr)
- {
- l = &(l->item->nextListItem);
- --index;
- }
-
- l->insertNext (newItem);
- }
-
- /** Replaces the object that this pointer points to, appending the rest of the list to
- the new object, and returning the old one.
- */
- ObjectType* replaceNext (ObjectType* const newItem) noexcept
- {
- bassert (newItem != nullptr);
- bassert (newItem->nextListItem == nullptr);
-
- ObjectType* const oldItem = item;
- item = newItem;
- item->nextListItem = oldItem->nextListItem.item;
- oldItem->nextListItem.item = nullptr;
- return oldItem;
- }
-
- /** Adds an item to the end of the list.
-
- This operation involves iterating the whole list, so can be slow - if you need to
- append a number of items to your list, it's much more efficient to use the Appender
- class than to repeatedly call append().
- */
- void append (ObjectType* const newItem)
- {
- getLast().item = newItem;
- }
-
- /** Creates copies of all the items in another list and adds them to this one.
- This will use the ObjectType's copy constructor to try to create copies of each
- item in the other list, and appends them to this list.
- */
- void addCopyOfList (const LinkedListPointer& other)
- {
- LinkedListPointer* insertPoint = this;
-
- for (ObjectType* i = other.item; i != nullptr; i = i->nextListItem)
- {
- insertPoint->insertNext (new ObjectType (*i));
- insertPoint = &(insertPoint->item->nextListItem);
- }
- }
-
- /** Removes the head item from the list.
- This won't delete the object that is removed, but returns it, so the caller can
- delete it if necessary.
- */
- ObjectType* removeNext() noexcept
- {
- ObjectType* const oldItem = item;
-
- if (oldItem != nullptr)
- {
- item = oldItem->nextListItem;
- oldItem->nextListItem.item = nullptr;
- }
-
- return oldItem;
- }
-
- /** Removes a specific item from the list.
- Note that this will not delete the item, it simply unlinks it from the list.
- */
- void remove (ObjectType* const itemToRemove)
- {
- if (LinkedListPointer* const l = findPointerTo (itemToRemove))
- l->removeNext();
- }
-
- /** Iterates the list, calling the delete operator on all of its elements and
- leaving this pointer empty.
- */
- void deleteAll()
- {
- while (item != nullptr)
- {
- ObjectType* const oldItem = item;
- item = oldItem->nextListItem;
- delete oldItem;
- }
- }
-
- /** Finds a pointer to a given item.
- If the item is found in the list, this returns the pointer that points to it. If
- the item isn't found, this returns null.
- */
- LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) noexcept
- {
- LinkedListPointer* l = this;
-
- while (l->item != nullptr)
- {
- if (l->item == itemToLookFor)
- return l;
-
- l = &(l->item->nextListItem);
- }
-
- return nullptr;
- }
-
- /** Copies the items in the list to an array.
- The destArray must contain enough elements to hold the entire list - no checks are
- made for this!
- */
- void copyToArray (ObjectType** destArray) const noexcept
- {
- bassert (destArray != nullptr);
-
- for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
- *destArray++ = i;
- }
-
- /** Swaps this pointer with another one */
- void swapWith (LinkedListPointer& other) noexcept
- {
- std::swap (item, other.item);
- }
-
- //==============================================================================
- /**
- Allows efficient repeated insertions into a list.
-
- You can create an Appender object which points to the last element in your
- list, and then repeatedly call Appender::append() to add items to the end
- of the list in O(1) time.
- */
- class Appender
- {
- public:
- /** Creates an appender which will add items to the given list.
- */
- Appender (LinkedListPointer& endOfListPointer) noexcept
- : endOfList (&endOfListPointer)
- {
- // This can only be used to add to the end of a list.
- bassert (endOfListPointer.item == nullptr);
- }
-
- Appender(LinkedListPointer const&) = delete;
- Appender& operator= (Appender const&) = delete;
-
- /** Appends an item to the list. */
- void append (ObjectType* const newItem) noexcept
- {
- *endOfList = newItem;
- endOfList = &(newItem->nextListItem);
- }
-
- private:
- LinkedListPointer* endOfList;
- };
-
-private:
- //==============================================================================
- ObjectType* item;
-};
-
-} // beast
-
-#endif // BEAST_LINKEDLISTPOINTER_H_INCLUDED
diff --git a/src/beast/beast/module/core/containers/ScopedValueSetter.h b/src/beast/beast/module/core/containers/ScopedValueSetter.h
deleted file mode 100644
index f1c82f352a..0000000000
--- a/src/beast/beast/module/core/containers/ScopedValueSetter.h
+++ /dev/null
@@ -1,99 +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_SCOPEDVALUESETTER_H_INCLUDED
-#define BEAST_SCOPEDVALUESETTER_H_INCLUDED
-
-namespace beast
-{
-
-//==============================================================================
-/**
- Helper class providing an RAII-based mechanism for temporarily setting and
- then re-setting a value.
-
- E.g. @code
- int x = 1;
-
- {
- ScopedValueSetter setter (x, 2);
-
- // x is now 2
- }
-
- // x is now 1 again
-
- {
- ScopedValueSetter setter (x, 3, 4);
-
- // x is now 3
- }
-
- // x is now 4
- @endcode
-
-*/
-template
-class ScopedValueSetter
-{
-public:
- /** Creates a ScopedValueSetter that will immediately change the specified value to the
- given new value, and will then reset it to its original value when this object is deleted.
- */
- ScopedValueSetter (ValueType& valueToSet,
- ValueType newValue)
- : value (valueToSet),
- originalValue (valueToSet)
- {
- valueToSet = newValue;
- }
-
- /** Creates a ScopedValueSetter that will immediately change the specified value to the
- given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
- */
- ScopedValueSetter (ValueType& valueToSet,
- ValueType newValue,
- ValueType valueWhenDeleted)
- : value (valueToSet),
- originalValue (valueWhenDeleted)
- {
- valueToSet = newValue;
- }
-
- ScopedValueSetter(ScopedValueSetter const&) = delete;
- ScopedValueSetter& operator= (ScopedValueSetter const&) = delete;
-
- ~ScopedValueSetter()
- {
- value = originalValue;
- }
-
-private:
- //==============================================================================
- ValueType& value;
- const ValueType originalValue;
-};
-
-} // beast
-
-#endif // BEAST_SCOPEDVALUESETTER_H_INCLUDED
diff --git a/src/beast/beast/module/core/core.h b/src/beast/beast/module/core/core.h
index fccd3a50cb..c38a27f0c1 100644
--- a/src/beast/beast/module/core/core.h
+++ b/src/beast/beast/module/core/core.h
@@ -41,7 +41,6 @@
// New header-only library modeled more closely according to boost
#include
-#include
#include
#include
#include
@@ -136,13 +135,9 @@ class FileOutputStream;
#include
#include
#include
-#include
#include
-#include
#include
#include
-#include
-#include
#include
#include
#include
@@ -150,17 +145,11 @@ class FileOutputStream;
#include
#include
#include
-#include
-#include
-#include
-#include
#include
-#include
#include
#include
#include
-#include
#include
#include
diff --git a/src/beast/beast/module/core/core.unity.cpp b/src/beast/beast/module/core/core.unity.cpp
index aa6a0756b5..7d74933a53 100644
--- a/src/beast/beast/module/core/core.unity.cpp
+++ b/src/beast/beast/module/core/core.unity.cpp
@@ -134,11 +134,6 @@
#include
#include
#include
-#include
-#include
-#include
-
-#include
#include
@@ -182,9 +177,7 @@
#include
#elif BEAST_WINDOWS
-#include
#include
-#include
#include
#include
diff --git a/src/beast/beast/module/core/diagnostic/FatalError.cpp b/src/beast/beast/module/core/diagnostic/FatalError.cpp
index 90cd601ef1..3add7cbe76 100644
--- a/src/beast/beast/module/core/diagnostic/FatalError.cpp
+++ b/src/beast/beast/module/core/diagnostic/FatalError.cpp
@@ -26,45 +26,50 @@ namespace beast {
// FatalError::Reporter
//
void FatalError::Reporter::onFatalError (
- char const* message, char const* stackBacktrace, char const* filePath, int lineNumber)
+ char const* message,
+ char const* backtrace,
+ char const* filePath,
+ int lineNumber)
{
- String formattedMessage = formatMessage (
- message, stackBacktrace, filePath, lineNumber);
-
- reportMessage (formattedMessage);
+ reportMessage (formatMessage (message, backtrace, filePath, lineNumber));
}
-void FatalError::Reporter::reportMessage (String& formattedMessage)
+void FatalError::Reporter::reportMessage (std::string const& message)
{
- std::cerr << formattedMessage.toRawUTF8 ();
+ std::cerr << message << std::endl;
}
-String FatalError::Reporter::formatMessage (
- char const* message, char const* stackBacktrace, char const* filePath, int lineNumber)
+std::string FatalError::Reporter::formatMessage (
+ char const* message,
+ char const* backtrace,
+ char const* filePath,
+ int lineNumber)
{
- String formattedMessage;
- formattedMessage.preallocateBytes (16 * 1024);
+ std::string output;
+ output.reserve (16 * 1024);
- formattedMessage << message;
+ output.append (message);
if (filePath != nullptr && filePath [0] != 0)
{
- formattedMessage << ", in " << formatFilePath (filePath)
- << " line " << String (lineNumber);
+ output.append (", in ");
+ output.append (formatFilePath (filePath));
+ output.append (" line ");
+ output.append (std::to_string (lineNumber));
}
- formattedMessage << newLine;
+ output.append ("\n");
- if (stackBacktrace != nullptr && stackBacktrace [0] != 0)
+ if (backtrace != nullptr && backtrace[0] != 0)
{
- formattedMessage << "Stack:" << newLine;
- formattedMessage << stackBacktrace;
+ output.append ("Stack:\n");
+ output.append (backtrace);
}
- return formattedMessage;
+ return output;
}
-String FatalError::Reporter::formatFilePath (char const* filePath)
+std::string FatalError::Reporter::formatFilePath (char const* filePath)
{
return filePath;
}
@@ -94,19 +99,13 @@ FatalError::FatalError (char const* message, char const* fileName, int lineNumbe
std::lock_guard lock (s_mutex);
- String const backtraceString = SystemStats::getStackBacktrace ();
+ auto const backtrace = SystemStats::getStackBacktrace ();
- char const* const szStackBacktrace = backtraceString.toRawUTF8 ();
-
- String const fileNameString = fileName;
-
- char const* const szFileName = fileNameString.toRawUTF8 ();
-
- Reporter* const reporter (s_reporter);
+ Reporter* const reporter = s_reporter;
if (reporter != nullptr)
{
- reporter->onFatalError (message, szStackBacktrace, szFileName, lineNumber);
+ reporter->onFatalError (message, backtrace.c_str (), fileName, lineNumber);
}
Process::terminate ();
diff --git a/src/beast/beast/module/core/diagnostic/FatalError.h b/src/beast/beast/module/core/diagnostic/FatalError.h
index 0a482dedec..d91c8bb4dd 100644
--- a/src/beast/beast/module/core/diagnostic/FatalError.h
+++ b/src/beast/beast/module/core/diagnostic/FatalError.h
@@ -68,7 +68,7 @@ public:
@param lineNumber The line number in the source file.
*/
virtual void onFatalError (char const* message,
- char const* stackBacktrace,
+ char const* backtrace,
char const* filePath,
int lineNumber);
@@ -80,7 +80,7 @@ public:
@param formattedMessage The message to report.
*/
- virtual void reportMessage (String& formattedMessage);
+ virtual void reportMessage (std::string const& formattedMessage);
protected:
/** Called to format the message.
@@ -96,10 +96,11 @@ public:
@param filePath The file path from the report.
@param lineNumber The line number from the report
*/
- virtual String formatMessage (char const* message,
- char const* stackBacktrace,
- char const* filePath,
- int lineNumber);
+ virtual std::string formatMessage (
+ char const* message,
+ char const* backtrace,
+ char const* filePath,
+ int lineNumber);
/** Call to reformat the file path.
@@ -111,7 +112,7 @@ public:
You can override this to do a custom format on the file path.
*/
- virtual String formatFilePath (char const* filePath);
+ virtual std::string formatFilePath (char const* filePath);
};
/** Returns the current fatal error reporter. */
diff --git a/src/beast/beast/module/core/diagnostic/SemanticVersion.cpp b/src/beast/beast/module/core/diagnostic/SemanticVersion.cpp
index aafba52564..aba2dc7588 100644
--- a/src/beast/beast/module/core/diagnostic/SemanticVersion.cpp
+++ b/src/beast/beast/module/core/diagnostic/SemanticVersion.cpp
@@ -272,7 +272,7 @@ int compare (SemanticVersion const& lhs, SemanticVersion const& rhs)
return -1;
// Compare pre-release identifiers
- for (int i = 0; i < bmax (lhs.preReleaseIdentifiers.size (), rhs.preReleaseIdentifiers.size ()); ++i)
+ for (int i = 0; i < std::max (lhs.preReleaseIdentifiers.size (), rhs.preReleaseIdentifiers.size ()); ++i)
{
// A larger list of identifiers has a higher precedence
if (i >= rhs.preReleaseIdentifiers.size ())
diff --git a/src/beast/beast/module/core/files/File.cpp b/src/beast/beast/module/core/files/File.cpp
index 9bf40a1d7a..1048981ac2 100644
--- a/src/beast/beast/module/core/files/File.cpp
+++ b/src/beast/beast/module/core/files/File.cpp
@@ -22,6 +22,8 @@
//==============================================================================
#include
+
+#include
#include
namespace beast {
@@ -168,10 +170,6 @@ String File::parseAbsolutePath (const String& p)
path if that's what was supplied, or would evaluate a partial path relative to the CWD.
*/
bassertfalse;
-
- #if BEAST_LOG_ASSERTIONS
- Logger::writeToLog ("Illegal absolute path: " + path);
- #endif
}
#endif
@@ -422,21 +420,6 @@ File File::getSiblingFile (const String& fileName) const
return getParentDirectory().getChildFile (fileName);
}
-//==============================================================================
-String File::descriptionOfSizeInBytes (const std::int64_t bytes)
-{
- const char* suffix;
- double divisor = 0;
-
- if (bytes == 1) { suffix = " byte"; }
- else if (bytes < 1024) { suffix = " bytes"; }
- else if (bytes < 1024 * 1024) { suffix = " KB"; divisor = 1024.0; }
- else if (bytes < 1024 * 1024 * 1024) { suffix = " MB"; divisor = 1024.0 * 1024.0; }
- else { suffix = " GB"; divisor = 1024.0 * 1024.0 * 1024.0; }
-
- return (divisor > 0 ? String (bytes / divisor, 1) : String (bytes)) + suffix;
-}
-
//==============================================================================
Result File::create() const
{
@@ -486,31 +469,6 @@ bool File::setLastModificationTime (Time t) const { return setFileTimesIntern
bool File::setLastAccessTime (Time t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
bool File::setCreationTime (Time t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
-//==============================================================================
-bool File::loadFileAsData (MemoryBlock& destBlock) const
-{
- if (! existsAsFile())
- return false;
-
- FileInputStream in (*this);
- return in.openedOk() && getSize() == in.readIntoMemoryBlock (destBlock);
-}
-
-String File::loadFileAsString() const
-{
- if (! existsAsFile())
- return String::empty;
-
- FileInputStream in (*this);
- return in.openedOk() ? in.readEntireStreamAsString()
- : String::empty;
-}
-
-void File::readLines (StringArray& destLines) const
-{
- destLines.addLines (loadFileAsString());
-}
-
//==============================================================================
int File::findChildFiles (Array& results,
const int whatToLookFor,
@@ -666,12 +624,6 @@ File File::withFileExtension (const String& newExtension) const
return getSiblingFile (filePart + newExtension);
}
-//==============================================================================
-bool File::startAsProcess (const String& parameters) const
-{
- return exists() && Process::openDocument (fullPath, parameters);
-}
-
//==============================================================================
FileInputStream* File::createInputStream() const
{
@@ -704,17 +656,6 @@ bool File::appendData (const void* const dataToAppend,
return out.openedOk() && out.write (dataToAppend, numberOfBytes);
}
-bool File::replaceWithData (const void* const dataToWrite,
- const size_t numberOfBytes) const
-{
- if (numberOfBytes == 0)
- return deleteFile();
-
- TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
- tempFile.getFile().appendData (dataToWrite, numberOfBytes);
- return tempFile.overwriteTargetFileWithTemporary();
-}
-
bool File::appendText (const String& text,
const bool asUnicode,
const bool writeUnicodeHeaderBytes) const
@@ -728,49 +669,6 @@ bool File::appendText (const String& text,
return true;
}
-bool File::replaceWithText (const String& textToWrite,
- const bool asUnicode,
- const bool writeUnicodeHeaderBytes) const
-{
- TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
- tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
- return tempFile.overwriteTargetFileWithTemporary();
-}
-
-bool File::hasIdenticalContentTo (const File& other) const
-{
- if (other == *this)
- return true;
-
- if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
- {
- FileInputStream in1 (*this), in2 (other);
-
- if (in1.openedOk() && in2.openedOk())
- {
- const int bufferSize = 4096;
- HeapBlock buffer1 (bufferSize), buffer2 (bufferSize);
-
- for (;;)
- {
- const int num1 = in1.read (buffer1, bufferSize);
- const int num2 = in2.read (buffer2, bufferSize);
-
- if (num1 != num2)
- break;
-
- if (num1 <= 0)
- return true;
-
- if (memcmp (buffer1, buffer2, (size_t) num1) != 0)
- break;
- }
- }
- }
-
- return false;
-}
-
//==============================================================================
String File::createLegalPathName (const String& original)
{
@@ -798,7 +696,7 @@ String File::createLegalFileName (const String& original)
{
const int lastDot = s.lastIndexOfChar ('.');
- if (lastDot > bmax (0, len - 12))
+ if (lastDot > std::max (0, len - 12))
{
s = s.substring (0, maxLength - (len - lastDot))
+ s.substring (lastDot);
@@ -929,34 +827,14 @@ public:
expect (! home.existsAsFile());
expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
- expect (File::getSpecialLocation (File::currentExecutableFile).exists());
- expect (File::getSpecialLocation (File::currentApplicationFile).exists());
- expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
expect (home.getVolumeTotalSize() > 1024 * 1024);
expect (home.getBytesFreeOnVolume() > 0);
- expect (! home.isHidden());
- expect (home.isOnHardDisk());
- expect (! home.isOnCDRomDrive());
expect (File::getCurrentWorkingDirectory().exists());
expect (home.setAsCurrentWorkingDirectory());
#if BEAST_WINDOWS
expect (File::getCurrentWorkingDirectory() == home);
#endif
- {
- Array roots;
- File::findFileSystemRoots (roots);
- expect (roots.size() > 0);
-
- int numRootsExisting = 0;
- for (int i = 0; i < roots.size(); ++i)
- if (roots[i].exists())
- ++numRootsExisting;
-
- // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
- expect (numRootsExisting > 0);
- }
-
testcase ("Writing");
File demoFolder (temp.getChildFile ("Beast UnitTests Temp Folder.folder"));
@@ -998,7 +876,6 @@ public:
expect (tempFile.exists());
expect (tempFile.getSize() == 10);
expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
- expect (tempFile.loadFileAsString() == String ("0123456789"));
expect (! demoFolder.containsSubDirectories());
expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
@@ -1023,13 +900,6 @@ public:
Time t2 = tempFile.getLastModificationTime();
expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
- {
- MemoryBlock mb;
- tempFile.loadFileAsData (mb);
- expect (mb.getSize() == 10);
- expect (mb[0] == '0');
- }
-
{
expect (tempFile.getSize() == 10);
FileOutputStream fo (tempFile);
@@ -1047,13 +917,10 @@ public:
expect (tempFile.appendData ("abcdefghij", 10));
expect (tempFile.getSize() == 20);
- expect (tempFile.replaceWithData ("abcdefghij", 10));
- expect (tempFile.getSize() == 10);
File tempFile2 (tempFile.getNonexistentSibling (false));
expect (tempFile.copyFileTo (tempFile2));
expect (tempFile2.exists());
- expect (tempFile2.hasIdenticalContentTo (tempFile));
expect (tempFile.deleteFile());
expect (! tempFile.exists());
expect (tempFile2.moveFileTo (tempFile));
diff --git a/src/beast/beast/module/core/files/File.h b/src/beast/beast/module/core/files/File.h
index cee8d93113..32c65d4b79 100644
--- a/src/beast/beast/module/core/files/File.h
+++ b/src/beast/beast/module/core/files/File.h
@@ -134,13 +134,6 @@ public:
*/
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 (std::int64_t bytes);
-
//==============================================================================
/** Returns the complete, absolute path of this file.
@@ -354,16 +347,6 @@ public:
bool setReadOnly (bool shouldBeReadOnly,
bool applyRecursively = false) const;
- /** Returns true if this file is a hidden or system file.
- The criteria for deciding whether a file is hidden are platform-dependent.
- */
- bool isHidden() const;
-
- /** If this file is a link, this returns the file that it points to.
- If this file isn't actually link, it'll just return itself.
- */
- File getLinkedTarget() const;
-
//==============================================================================
/** Returns the last modification time of this file.
@@ -410,14 +393,6 @@ public:
*/
bool setCreationTime (Time newTime) const;
- /** If possible, this will try to create a version string for the given file.
-
- The OS may be able to look at the file and give a version for it - e.g. with
- executables, bundles, dlls, etc. If no version is available, this will
- return an empty string.
- */
- String getVersion() const;
-
//==============================================================================
/** Creates an empty file if it doesn't already exist.
@@ -464,14 +439,6 @@ public:
*/
bool deleteRecursively() const;
- /** Moves this file or folder to the trash.
-
- @returns true if the operation succeeded. It could fail if the trash is full, or
- if the file is write-protected, so you should check the return value
- and act appropriately.
- */
- bool moveToTrash() const;
-
/** Moves or renames a file.
Tries to move a file to a different location.
@@ -572,7 +539,7 @@ public:
@returns a stream that will read from this file (initially positioned at the
start of the file), or nullptr if the file can't be opened for some reason
- @see createOutputStream, loadFileAsData
+ @see createOutputStream
*/
FileInputStream* createInputStream() const;
@@ -588,33 +555,6 @@ public:
*/
FileOutputStream* createOutputStream (size_t bufferSize = 0x8000) const;
- //==============================================================================
- /** Loads a file's contents into memory as a block of binary data.
-
- Of course, trying to load a very large file into memory will blow up, so
- it's better to check first.
-
- @param result the data block to which the file's contents should be appended - note
- that if the memory block might already contain some data, you
- might want to clear it first
- @returns true if the file could all be read into memory
- */
- bool loadFileAsData (MemoryBlock& result) const;
-
- /** Reads a file into memory as a string.
-
- Attempts to load the entire file as a zero-terminated string.
-
- This makes use of InputStream::readEntireStreamAsString, which can
- read either UTF-16 or UTF-8 file formats.
- */
- String loadFileAsString() const;
-
- /** Reads the contents of this file as text and splits it into lines, which are
- appended to the given StringArray.
- */
- void readLines (StringArray& destLines) const;
-
//==============================================================================
/** Appends a block of binary data to the end of the file.
@@ -625,23 +565,6 @@ public:
bool appendData (const void* dataToAppend,
size_t numberOfBytes) const;
- /** Replaces this file's contents with a given block of data.
-
- This will delete the file and replace it with the given data.
-
- A nice feature of this method is that it's safe - instead of deleting
- the file first and then re-writing it, it creates a new temporary file,
- writes the data to that, and then moves the new file to replace the existing
- file. This means that if the power gets pulled out or something crashes,
- you're a lot less likely to end up with a corrupted or unfinished file..
-
- Returns true if the operation succeeds, or false if it fails.
-
- @see appendText
- */
- bool replaceWithData (const void* dataToWrite,
- size_t numberOfBytes) const;
-
/** Appends a string to the end of the file.
This will try to append a text string to the file, as either 16-bit unicode
@@ -658,50 +581,7 @@ public:
bool asUnicode = false,
bool writeUnicodeHeaderBytes = false) const;
- /** Replaces this file's contents with a given text string.
-
- This will delete the file and replace it with the given text.
-
- A nice feature of this method is that it's safe - instead of deleting
- the file first and then re-writing it, it creates a new temporary file,
- writes the text to that, and then moves the new file to replace the existing
- file. This means that if the power gets pulled out or something crashes,
- you're a lot less likely to end up with an empty file..
-
- For an explanation of the parameters here, see the appendText() method.
-
- Returns true if the operation succeeds, or false if it fails.
-
- @see appendText
- */
- bool replaceWithText (const String& textToWrite,
- bool asUnicode = false,
- bool writeUnicodeHeaderBytes = false) const;
-
- /** Attempts to scan the contents of this file and compare it to another file, returning
- true if this is possible and they match byte-for-byte.
- */
- bool hasIdenticalContentTo (const File& other) const;
-
//==============================================================================
- /** Creates a set of files to represent each file root.
-
- e.g. on Windows this will create files for "c:\", "d:\" etc according
- to which ones are available. On the Mac/Linux, this will probably
- just add a single entry for "/".
- */
- static void findFileSystemRoots (Array& results);
-
- /** Finds the name of the drive on which this file lives.
- @returns the volume label of the drive, or an empty string if this isn't possible
- */
- String getVolumeLabel() const;
-
- /** Returns the serial number of the volume on which this file lives.
- @returns the serial number, or zero if there's a problem doing this
- */
- int getVolumeSerialNumber() const;
-
/** Returns the number of bytes free on the drive that this file lives on.
@returns the number of bytes free, or 0 if there's a problem finding this out
@@ -716,41 +596,6 @@ public:
*/
std::int64_t getVolumeTotalSize() const;
- /** Returns true if this file is on a CD or DVD drive. */
- bool isOnCDRomDrive() const;
-
- /** Returns true if this file is on a hard disk.
-
- This will fail if it's a network drive, but will still be true for
- removable hard-disks.
- */
- bool isOnHardDisk() const;
-
- /** Returns true if this file is on a removable disk drive.
-
- This might be a usb-drive, a CD-rom, or maybe a network drive.
- */
- bool isOnRemovableDrive() const;
-
- //==============================================================================
- /** Launches the file as a process.
-
- - if the file is executable, this will run it.
-
- - if it's a document of some kind, it will launch the document with its
- default viewer application.
-
- - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
-
- @see revealToUser
- */
- bool startAsProcess (const String& parameters = String::empty) const;
-
- /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
- @see startAsProcess
- */
- void revealToUser() const;
-
//==============================================================================
/** A set of types of location that can be passed to the getSpecialLocation() method.
*/
@@ -806,39 +651,6 @@ public:
*/
tempDirectory,
- /** Returns this application's executable file.
-
- If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
- host app.
-
- On the mac this will return the unix binary, not the package folder - see
- currentApplicationFile for that.
-
- See also invokedExecutableFile, which is similar, but if the exe was launched from a
- file link, invokedExecutableFile will return the name of the link.
- */
- currentExecutableFile,
-
- /** Returns this application's location.
-
- If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
- host app.
-
- On the mac this will return the package folder (if it's in one), not the unix binary
- that's inside it - compare with currentExecutableFile.
- */
- currentApplicationFile,
-
- /** Returns the file that was invoked to launch this executable.
- This may differ from currentExecutableFile if the app was started from e.g. a link - this
- will return the name of the link that was used, whereas currentExecutableFile will return
- the actual location of the target executable.
- */
- invokedExecutableFile,
-
- /** In a plugin, this will return the path of the host executable. */
- hostApplicationPath,
-
/** The directory in which applications normally get installed.
So on windows, this would be something like "c:\program files", on the
Mac "/Applications", or "/usr" on linux.
@@ -926,25 +738,6 @@ public:
/** Adds a separator character to the end of a path if it doesn't already have one. */
static String addTrailingSeparator (const String& path);
- #if BEAST_MAC || BEAST_IOS || DOXYGEN
- //==============================================================================
- /** OSX ONLY - Finds the OSType of a file from the its resources. */
- OSType getMacOSType() const;
-
- /** OSX ONLY - Returns true if this file is actually a bundle. */
- bool isBundle() const;
- #endif
-
- #if BEAST_MAC || DOXYGEN
- /** OSX ONLY - Adds this file to the OSX dock */
- void addToDock() const;
- #endif
-
- #if BEAST_WINDOWS
- /** Windows ONLY - Creates a win32 .LNK shortcut file that links to this file. */
- bool createLink (const String& description, const File& linkFileToCreate) const;
- #endif
-
private:
//==============================================================================
String fullPath;
diff --git a/src/beast/beast/module/core/files/FileOutputStream.cpp b/src/beast/beast/module/core/files/FileOutputStream.cpp
index 0300ebc668..4e7eaa4bc4 100644
--- a/src/beast/beast/module/core/files/FileOutputStream.cpp
+++ b/src/beast/beast/module/core/files/FileOutputStream.cpp
@@ -21,6 +21,8 @@
*/
//==============================================================================
+#include
+
namespace beast
{
@@ -34,7 +36,7 @@ FileOutputStream::FileOutputStream (const File& f, const size_t bufferSizeToUse)
currentPosition (0),
bufferSize (bufferSizeToUse),
bytesInBuffer (0),
- buffer (bmax (bufferSizeToUse, (size_t) 16))
+ buffer (std::max (bufferSizeToUse, (size_t) 16))
{
openHandle();
}
diff --git a/src/beast/beast/module/core/files/FileOutputStream.h b/src/beast/beast/module/core/files/FileOutputStream.h
index d8594724eb..53f1dad8ce 100644
--- a/src/beast/beast/module/core/files/FileOutputStream.h
+++ b/src/beast/beast/module/core/files/FileOutputStream.h
@@ -49,8 +49,6 @@ public:
be set to the end of the file. To overwrite an existing file,
use File::deleteFile() before opening the stream, or use setPosition(0)
after it's opened (although this won't truncate the file).
-
- @see TemporaryFile
*/
FileOutputStream (const File& fileToWriteTo,
size_t bufferSizeToUse = 16384);
diff --git a/src/beast/beast/module/core/files/FileSearchPath.cpp b/src/beast/beast/module/core/files/FileSearchPath.cpp
deleted file mode 100644
index ee47fc5bb6..0000000000
--- a/src/beast/beast/module/core/files/FileSearchPath.cpp
+++ /dev/null
@@ -1,171 +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
-{
-
-FileSearchPath::FileSearchPath()
-{
-}
-
-FileSearchPath::FileSearchPath (const String& path)
-{
- init (path);
-}
-
-FileSearchPath::FileSearchPath (const FileSearchPath& other)
- : directories (other.directories)
-{
-}
-
-FileSearchPath::~FileSearchPath()
-{
-}
-
-FileSearchPath& FileSearchPath::operator= (const String& path)
-{
- init (path);
- return *this;
-}
-
-void FileSearchPath::init (const String& path)
-{
- directories.clear();
- directories.addTokens (path, ";", "\"");
- directories.trim();
- directories.removeEmptyStrings();
-
- for (int i = directories.size(); --i >= 0;)
- directories.set (i, directories[i].unquoted());
-}
-
-int FileSearchPath::getNumPaths() const
-{
- return directories.size();
-}
-
-File FileSearchPath::operator[] (const int index) const
-{
- return File (directories [index]);
-}
-
-String FileSearchPath::toString() const
-{
- StringArray directories2 (directories);
- for (int i = directories2.size(); --i >= 0;)
- if (directories2[i].containsChar (';'))
- directories2.set (i, directories2[i].quoted());
-
- return directories2.joinIntoString (";");
-}
-
-void FileSearchPath::add (const File& dir, const int insertIndex)
-{
- directories.insert (insertIndex, dir.getFullPathName());
-}
-
-void FileSearchPath::addIfNotAlreadyThere (const File& dir)
-{
- for (int i = 0; i < directories.size(); ++i)
- if (File (directories[i]) == dir)
- return;
-
- add (dir);
-}
-
-void FileSearchPath::remove (const int index)
-{
- directories.remove (index);
-}
-
-void FileSearchPath::addPath (const FileSearchPath& other)
-{
- for (int i = 0; i < other.getNumPaths(); ++i)
- addIfNotAlreadyThere (other[i]);
-}
-
-void FileSearchPath::removeRedundantPaths()
-{
- for (int i = directories.size(); --i >= 0;)
- {
- const File d1 (directories[i]);
-
- for (int j = directories.size(); --j >= 0;)
- {
- const File d2 (directories[j]);
-
- if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
- {
- directories.remove (i);
- break;
- }
- }
- }
-}
-
-void FileSearchPath::removeNonExistentPaths()
-{
- for (int i = directories.size(); --i >= 0;)
- if (! File (directories[i]).isDirectory())
- directories.remove (i);
-}
-
-int FileSearchPath::findChildFiles (Array& results,
- const int whatToLookFor,
- const bool searchRecursively,
- const String& wildCardPattern) const
-{
- int total = 0;
-
- for (int i = 0; i < directories.size(); ++i)
- total += operator[] (i).findChildFiles (results,
- whatToLookFor,
- searchRecursively,
- wildCardPattern);
-
- return total;
-}
-
-bool FileSearchPath::isFileInPath (const File& fileToCheck,
- const bool checkRecursively) const
-{
- for (int i = directories.size(); --i >= 0;)
- {
- const File d (directories[i]);
-
- if (checkRecursively)
- {
- if (fileToCheck.isAChildOf (d))
- return true;
- }
- else
- {
- if (fileToCheck.getParentDirectory() == d)
- return true;
- }
- }
-
- return false;
-}
-
-} // beast
diff --git a/src/beast/beast/module/core/files/FileSearchPath.h b/src/beast/beast/module/core/files/FileSearchPath.h
deleted file mode 100644
index 7e897a2b3e..0000000000
--- a/src/beast/beast/module/core/files/FileSearchPath.h
+++ /dev/null
@@ -1,163 +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_FILESEARCHPATH_H_INCLUDED
-#define BEAST_FILESEARCHPATH_H_INCLUDED
-
-namespace beast
-{
-
-//==============================================================================
-/**
- Encapsulates a set of folders that make up a search path.
-
- @see File
-*/
-class FileSearchPath : LeakChecked
-{
-public:
- //==============================================================================
- /** Creates an empty search path. */
- FileSearchPath();
-
- /** Creates a search path from a string of pathnames.
-
- The path can be semicolon- or comma-separated, e.g.
- "/foo/bar;/foo/moose;/fish/moose"
-
- The separate folders are tokenised and added to the search path.
- */
- FileSearchPath (const String& path);
-
- /** Creates a copy of another search path. */
- FileSearchPath (const FileSearchPath& other);
-
- /** Destructor. */
- ~FileSearchPath();
-
- /** Uses a string containing a list of pathnames to re-initialise this list.
-
- This search path is cleared and the semicolon- or comma-separated folders
- in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
- */
- FileSearchPath& operator= (const String& path);
-
- //==============================================================================
- /** Returns the number of folders in this search path.
-
- @see operator[]
- */
- int getNumPaths() const;
-
- /** Returns one of the folders in this search path.
-
- The file returned isn't guaranteed to actually be a valid directory.
-
- @see getNumPaths
- */
- File operator[] (int index) const;
-
- /** Returns the search path as a semicolon-separated list of directories. */
- String toString() const;
-
- //==============================================================================
- /** Adds a new directory to the search path.
-
- The new directory is added to the end of the list if the insertIndex parameter is
- less than zero, otherwise it is inserted at the given index.
- */
- void add (const File& directoryToAdd,
- int insertIndex = -1);
-
- /** Adds a new directory to the search path if it's not already in there. */
- void addIfNotAlreadyThere (const File& directoryToAdd);
-
- /** Removes a directory from the search path. */
- void remove (int indexToRemove);
-
- /** Merges another search path into this one.
-
- This will remove any duplicate directories.
- */
- void addPath (const FileSearchPath& other);
-
- /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
-
- If the search is intended to be recursive, there's no point having nested folders in the search
- path, because they'll just get searched twice and you'll get duplicate results.
-
- e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
- */
- void removeRedundantPaths();
-
- /** Removes any directories that don't actually exist. */
- void removeNonExistentPaths();
-
- //==============================================================================
- /** Searches the path for a wildcard.
-
- This will search all the directories in the search path in order, adding any
- matching files to the results array.
-
- @param results an array to append the results to
- @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
- return files, directories, or both.
- @param searchRecursively whether to recursively search the subdirectories too
- @param wildCardPattern a pattern to match against the filenames
- @returns the number of files added to the array
- @see File::findChildFiles
- */
- int findChildFiles (Array& results,
- int whatToLookFor,
- bool searchRecursively,
- const String& wildCardPattern = "*") const;
-
- //==============================================================================
- /** Finds out whether a file is inside one of the path's directories.
-
- This will return true if the specified file is a child of one of the
- directories specified by this path. Note that this doesn't actually do any
- searching or check that the files exist - it just looks at the pathnames
- to work out whether the file would be inside a directory.
-
- @param fileToCheck the file to look for
- @param checkRecursively if true, then this will return true if the file is inside a
- subfolder of one of the path's directories (at any depth). If false
- it will only return true if the file is actually a direct child
- of one of the directories.
- @see File::isAChildOf
-
- */
- bool isFileInPath (const File& fileToCheck,
- bool checkRecursively) const;
-
-private:
- //==============================================================================
- StringArray directories;
-
- void init (const String& path);
-};
-
-} // beast
-
-#endif // BEAST_FILESEARCHPATH_H_INCLUDED
diff --git a/src/beast/beast/module/core/files/RandomAccessFile.cpp b/src/beast/beast/module/core/files/RandomAccessFile.cpp
deleted file mode 100644
index 4d610ed1c6..0000000000
--- a/src/beast/beast/module/core/files/RandomAccessFile.cpp
+++ /dev/null
@@ -1,274 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-#include
-
-namespace beast {
-
-RandomAccessFile::RandomAccessFile () noexcept
- : fileHandle (nullptr)
- , currentPosition (0)
-{
-}
-
-RandomAccessFile::~RandomAccessFile ()
-{
- close ();
-}
-
-Result RandomAccessFile::open (File const& path, Mode mode)
-{
- close ();
-
- return nativeOpen (path, mode);
-}
-
-void RandomAccessFile::close ()
-{
- if (isOpen ())
- {
- nativeFlush ();
- nativeClose ();
- }
-}
-
-Result RandomAccessFile::setPosition (FileOffset newPosition)
-{
- if (newPosition != currentPosition)
- {
- // VFALCO NOTE I dislike return from the middle but
- // Result::ok() is showing up in the profile
- //
- return nativeSetPosition (newPosition);
- }
-
- return Result::ok ();
-}
-
-Result RandomAccessFile::read (void* buffer, ByteCount numBytes, ByteCount* pActualAmount)
-{
- return nativeRead (buffer, numBytes, pActualAmount);
-}
-
-Result RandomAccessFile::write (const void* data, ByteCount numBytes, ByteCount* pActualAmount)
-{
- bassert (data != nullptr && ((std::ptrdiff_t) numBytes) >= 0);
-
- Result result (Result::ok ());
-
- ByteCount amountWritten = 0;
-
- result = nativeWrite (data, numBytes, &amountWritten);
-
- if (result.wasOk ())
- currentPosition += amountWritten;
-
- if (pActualAmount != nullptr)
- *pActualAmount = amountWritten;
-
- return result;
-}
-
-Result RandomAccessFile::truncate ()
-{
- Result result = flush ();
-
- if (result.wasOk ())
- result = nativeTruncate ();
-
- return result;
-}
-
-Result RandomAccessFile::flush ()
-{
- return nativeFlush ();
-}
-
-//------------------------------------------------------------------------------
-
-class RandomAccessFile_test : public unit_test::suite
-{
-public:
- enum
- {
- maxPayload = 8192
- };
-
- /* For this test we will create a file which consists of a fixed
- number of variable length records. Each record is numbered sequentially
- starting at 0. To calculate the position of each record we first build
- a table of size/offset pairs using a pseudorandom number generator.
- */
- struct Record
- {
- int index;
- int bytes;
- int offset;
- };
-
- typedef HeapBlock Records;
-
- // Produce the pseudo-random set of records.
- static void createRecords (HeapBlock & records,
- int numRecords,
- int maxBytes,
- std::int64_t seedValue)
- {
- using namespace UnitTestUtilities;
-
- Random r (seedValue);
-
- records.malloc (numRecords);
-
- int offset = 0;
-
- for (int i = 0; i < numRecords; ++i)
- {
- int const bytes = r.nextInt (maxBytes) + 1;
-
- records [i].index = i;
- records [i].bytes = bytes;
- records [i].offset = offset;
-
- offset += bytes;
- }
-
- repeatableShuffle (numRecords, records, seedValue);
- }
-
- // Write all the records to the file.
- // The payload is pseudo-randomly generated.
- void writeRecords (RandomAccessFile& file,
- int numRecords,
- HeapBlock const& records,
- std::int64_t seedValue)
- {
- using namespace UnitTestUtilities;
-
- for (int i = 0; i < numRecords; ++i)
- {
- Payload p (records [i].bytes);
-
- p.repeatableRandomFill (records [i].bytes,
- records [i].bytes,
- records [i].index + seedValue);
-
- file.setPosition (records [i].offset);
-
- Result result = file.write (p.data.getData (), p.bytes);
-
- expect (result.wasOk (), "Should be ok");
- }
- }
-
- // Read the records and verify the consistency.
- void readRecords (RandomAccessFile& file,
- int numRecords,
- HeapBlock const& records,
- std::int64_t seedValue)
- {
- using namespace UnitTestUtilities;
-
- for (int i = 0; i < numRecords; ++i)
- {
- Record const& record (records [i]);
-
- int const bytes = record.bytes;
-
- Payload p1 (bytes);
- Payload p2 (bytes);
-
- p1.repeatableRandomFill (bytes, bytes, record.index + seedValue);
-
- file.setPosition (record.offset);
-
- Result result = file.read (p2.data.getData (), bytes);
-
- expect (result.wasOk (), "Should be ok");
-
- if (result.wasOk ())
- {
- p2.bytes = bytes;
-
- expect (p1 == p2, "Should be equal");
- }
- }
- }
-
- // Perform the test at the given buffer size.
- void testFile (int const numRecords)
- {
- using namespace UnitTestUtilities;
-
- int const seedValue = 50;
-
- std::stringstream ss;
- ss << numRecords << " records";
- testcase (ss.str());
-
- // Calculate the path
- File const path (File::createTempFile ("RandomAccessFile"));
-
- // Create a predictable set of records
- HeapBlock records (numRecords);
- createRecords (records, numRecords, maxPayload, seedValue);
-
- Result result (Result::ok ());
-
- {
- // Create the file
- RandomAccessFile file;
- result = file.open (path, RandomAccessFile::readWrite);
- expect (result.wasOk (), "Should be ok");
-
- if (result.wasOk ())
- {
- writeRecords (file, numRecords, records, seedValue);
-
- readRecords (file, numRecords, records, seedValue);
-
- repeatableShuffle (numRecords, records, seedValue);
-
- readRecords (file, numRecords, records, seedValue);
- }
- }
-
- if (result.wasOk ())
- {
- // Re-open the file in read only mode
- RandomAccessFile file;
- result = file.open (path, RandomAccessFile::readOnly);
- expect (result.wasOk (), "Should be ok");
-
- if (result.wasOk ())
- {
- readRecords (file, numRecords, records, seedValue);
- }
- }
- }
-
- void run ()
- {
- testFile (10000);
- }
-};
-
-BEAST_DEFINE_TESTSUITE(RandomAccessFile,beast_core,beast);
-
-} // beast
diff --git a/src/beast/beast/module/core/files/RandomAccessFile.h b/src/beast/beast/module/core/files/RandomAccessFile.h
deleted file mode 100644
index 673a366b94..0000000000
--- a/src/beast/beast/module/core/files/RandomAccessFile.h
+++ /dev/null
@@ -1,203 +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_RANDOMACCESSFILE_H_INCLUDED
-#define BEAST_RANDOMACCESSFILE_H_INCLUDED
-
-namespace beast
-{
-
-/** Provides random access reading and writing to an operating system file.
-
- This class wraps the underlying native operating system routines for
- opening and closing a file for reading and/or writing, seeking within
- the file, and performing read and write operations. There are also methods
- provided for obtaining an input or output stream which will work with
- the file.
-
- @note All files are opened in binary mode. No text newline conversions
- are performed.
-
- @note None of these members are thread safe. The caller is responsible
- for synchronization.
-
- @see FileInputStream, FileOutputStream
-*/
-class RandomAccessFile : LeakChecked
-{
-public:
- /** The type of an FileOffset.
-
- This can be useful when writing templates.
- */
- typedef std::int64_t FileOffset;
-
- /** The type of a byte count.
-
- This can be useful when writing templates.
- */
- typedef size_t ByteCount;
-
- /** The access mode.
-
- @see open
- */
- enum Mode
- {
- readOnly,
- readWrite
- };
-
- //==============================================================================
- /** Creates an unopened file object.
-
- @see open, isOpen
- */
- RandomAccessFile () noexcept;
-
- RandomAccessFile(RandomAccessFile const&) = delete;
- RandomAccessFile& operator= (RandomAccessFile const&) = delete;
-
- /** Destroy the file object.
-
- If the operating system file is open it will be closed.
- */
- ~RandomAccessFile ();
-
- /** Determine if a file is open.
-
- @return `true` if the operating system file is open.
- */
- bool isOpen () const noexcept { return fileHandle != nullptr; }
-
- /** Opens a file object.
-
- The file is opened with the specified permissions. The initial
- position is set to the beginning of the file.
-
- @note If a file is already open, it will be closed first.
-
- @param path The path to the file
- @param mode The access permissions
- @return An indication of the success of the operation.
-
- @see Mode
- */
- Result open (File const& path, Mode mode);
-
- /** Closes the file object.
-
- Any data that needs to be flushed will be written before the file is closed.
-
- @note If no file is opened, this call does nothing.
- */
- void close ();
-
- /** Retrieve the @ref File associated with this object.
-
- @return The associated @ref File.
- */
- File const& getFile () const noexcept { return file; }
-
- /** Get the current position.
-
- The next read or write will take place from here.
-
- @return The current position, as an absolute byte FileOffset from the begining.
- */
- FileOffset getPosition () const noexcept { return currentPosition; }
-
- /** Set the current position.
-
- The next read or write will take place at this location.
-
- @param newPosition The byte FileOffset from the beginning of the file to move to.
-
- @return `true` if the operation was successful.
- */
- Result setPosition (FileOffset newPosition);
-
- /** Read data at the current position.
-
- The caller is responsible for making sure that the memory pointed to
- by `buffer` is at least as large as `bytesToRead`.
-
- @note The file must have been opened with read permission.
-
- @param buffer The memory to store the incoming data
- @param numBytes The number of bytes to read.
- @param pActualAmount Pointer to store the actual amount read, or `nullptr`.
-
- @return `true` if all the bytes were read.
- */
- Result read (void* buffer, ByteCount numBytes, ByteCount* pActualAmount = 0);
-
- /** Write data at the current position.
-
- The current position is advanced past the data written. If data is
- written past the end of the file, the file size is increased on disk.
-
- The caller is responsible for making sure that the memory pointed to
- by `buffer` is at least as large as `bytesToWrite`.
-
- @note The file must have been opened with write permission.
-
- @param data A pointer to the data buffer to write to the file.
- @param numBytes The number of bytes to write.
- @param pActualAmount Pointer to store the actual amount written, or `nullptr`.
-
- @return `true` if all the data was written.
- */
- Result write (const void* data, ByteCount numBytes, ByteCount* pActualAmount = 0);
-
- /** Truncate the file at the current position.
- */
- Result truncate ();
-
- /** Flush the output buffers.
-
- This calls the operating system to make sure all data has been written.
- */
- Result flush();
-
- //==============================================================================
-private:
- // Some of these these methods are implemented natively on
- // the corresponding platform.
- //
- // See beast_posix_SharedCode.h and beast_win32_Files.cpp
- //
- Result nativeOpen (File const& path, Mode mode);
- void nativeClose ();
- Result nativeSetPosition (FileOffset newPosition);
- Result nativeRead (void* buffer, ByteCount numBytes, ByteCount* pActualAmount = 0);
- Result nativeWrite (const void* data, ByteCount numBytes, ByteCount* pActualAmount = 0);
- Result nativeTruncate ();
- Result nativeFlush ();
-
-private:
- File file;
- void* fileHandle;
- FileOffset currentPosition;
-};
-
-} // beast
-
-#endif
-
diff --git a/src/beast/beast/module/core/files/TemporaryFile.cpp b/src/beast/beast/module/core/files/TemporaryFile.cpp
deleted file mode 100644
index d552c34998..0000000000
--- a/src/beast/beast/module/core/files/TemporaryFile.cpp
+++ /dev/null
@@ -1,117 +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
-{
-
-static File createTempFile (const File& parentDirectory, String name,
- const String& suffix, const int optionFlags)
-{
- if ((optionFlags & TemporaryFile::useHiddenFile) != 0)
- name = "." + name;
-
- return parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & TemporaryFile::putNumbersInBrackets) != 0);
-}
-
-TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
- : temporaryFile (createTempFile (File::getSpecialLocation (File::tempDirectory),
- "temp_" + String::toHexString (Random::getSystemRandom().nextInt()),
- suffix, optionFlags))
-{
-}
-
-TemporaryFile::TemporaryFile (const File& target, const int optionFlags)
- : temporaryFile (createTempFile (target.getParentDirectory(),
- target.getFileNameWithoutExtension()
- + "_temp" + String::toHexString (Random::getSystemRandom().nextInt()),
- target.getFileExtension(), optionFlags)),
- targetFile (target)
-{
- // If you use this constructor, you need to give it a valid target file!
- bassert (targetFile != File::nonexistent ());
-}
-
-TemporaryFile::TemporaryFile (const File& target, const File& temporary)
- : temporaryFile (temporary), targetFile (target)
-{
-}
-
-TemporaryFile::~TemporaryFile()
-{
- if (! deleteTemporaryFile())
- {
- /* Failed to delete our temporary file! The most likely reason for this would be
- that you've not closed an output stream that was being used to write to file.
-
- If you find that something beyond your control is changing permissions on
- your temporary files and preventing them from being deleted, you may want to
- call TemporaryFile::deleteTemporaryFile() to detect those error cases and
- handle them appropriately.
- */
- bassertfalse;
- }
-}
-
-//==============================================================================
-bool TemporaryFile::overwriteTargetFileWithTemporary() const
-{
- // This method only works if you created this object with the constructor
- // that takes a target file!
- bassert (targetFile != File::nonexistent ());
-
- if (temporaryFile.exists())
- {
- // Have a few attempts at overwriting the file before giving up..
- for (int i = 5; --i >= 0;)
- {
- if (temporaryFile.moveFileTo (targetFile))
- return true;
-
- Thread::sleep (100);
- }
- }
- else
- {
- // There's no temporary file to use. If your write failed, you should
- // probably check, and not bother calling this method.
- bassertfalse;
- }
-
- return false;
-}
-
-bool TemporaryFile::deleteTemporaryFile() const
-{
- // Have a few attempts at deleting the file before giving up..
- for (int i = 5; --i >= 0;)
- {
- if (temporaryFile.deleteFile())
- return true;
-
- Thread::sleep (50);
- }
-
- return false;
-}
-
-} // beast
diff --git a/src/beast/beast/module/core/files/TemporaryFile.h b/src/beast/beast/module/core/files/TemporaryFile.h
deleted file mode 100644
index 7b1d3ed16d..0000000000
--- a/src/beast/beast/module/core/files/TemporaryFile.h
+++ /dev/null
@@ -1,169 +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_TEMPORARYFILE_H_INCLUDED
-#define BEAST_TEMPORARYFILE_H_INCLUDED
-
-namespace beast
-{
-
-//==============================================================================
-/**
- Manages a temporary file, which will be deleted when this object is deleted.
-
- This object is intended to be used as a stack based object, using its scope
- to make sure the temporary file isn't left lying around.
-
- For example:
-
- @code
- {
- File myTargetFile ("~/myfile.txt");
-
- // this will choose a file called something like "~/myfile_temp239348.txt"
- // which definitely doesn't exist at the time the constructor is called.
- TemporaryFile temp (myTargetFile);
-
- // create a stream to the temporary file, and write some data to it...
- std::unique_ptr out (temp.getFile().createOutputStream());
-
- if (out != nullptr)
- {
- out->write ( ...etc )
- out = nullptr; // (deletes the stream)
-
- // ..now we've finished writing, this will rename the temp file to
- // make it replace the target file we specified above.
- bool succeeded = temp.overwriteTargetFileWithTemporary();
- }
-
- // ..and even if something went wrong and our overwrite failed,
- // as the TemporaryFile object goes out of scope here, it'll make sure
- // that the temp file gets deleted.
- }
- @endcode
-
- @see File, FileOutputStream
-*/
-class TemporaryFile : LeakChecked
-{
-public:
- //==============================================================================
- enum OptionFlags
- {
- useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
- i.e. its name should start with a dot. */
- putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
- the file is unique, they should go in brackets rather
- than just being appended (see File::getNonexistentSibling() )*/
- };
-
- //==============================================================================
- /** Creates a randomly-named temporary file in the default temp directory.
-
- @param suffix a file suffix to use for the file
- @param optionFlags a combination of the values listed in the OptionFlags enum
- The file will not be created until you write to it. And remember that when
- this object is deleted, the file will also be deleted!
- */
- TemporaryFile (const String& suffix = String::empty,
- int optionFlags = 0);
-
- /** Creates a temporary file in the same directory as a specified file.
-
- This is useful if you have a file that you want to overwrite, but don't
- want to harm the original file if the write operation fails. You can
- use this to create a temporary file next to the target file, then
- write to the temporary file, and finally use overwriteTargetFileWithTemporary()
- to replace the target file with the one you've just written.
-
- This class won't create any files until you actually write to them. And remember
- that when this object is deleted, the temporary file will also be deleted!
-
- @param targetFile the file that you intend to overwrite - the temporary
- file will be created in the same directory as this
- @param optionFlags a combination of the values listed in the OptionFlags enum
- */
- TemporaryFile (const File& targetFile,
- int optionFlags = 0);
-
- /** Creates a temporary file using an explicit filename.
- The other constructors are a better choice than this one, unless for some reason
- you need to explicitly specify the temporary file you want to use.
-
- @param targetFile the file that you intend to overwrite
- @param temporaryFile the temporary file to be used
- */
- TemporaryFile (const File& targetFile,
- const File& temporaryFile);
-
- TemporaryFile(TemporaryFile const&) = delete;
- TemporaryFile& operator= (TemporaryFile const&) = delete;
-
- /** Destructor.
-
- When this object is deleted it will make sure that its temporary file is
- also deleted! If the operation fails, it'll throw an assertion in debug
- mode.
- */
- ~TemporaryFile();
-
- //==============================================================================
- /** Returns the temporary file. */
- const File& getFile() const noexcept { return temporaryFile; }
-
- /** Returns the target file that was specified in the constructor. */
- const File& getTargetFile() const noexcept { return targetFile; }
-
- /** Tries to move the temporary file to overwrite the target file that was
- specified in the constructor.
-
- If you used the constructor that specified a target file, this will attempt
- to replace that file with the temporary one.
-
- Before calling this, make sure:
- - that you've actually written to the temporary file
- - that you've closed any open streams that you were using to write to it
- - and that you don't have any streams open to the target file, which would
- prevent it being overwritten
-
- If the file move succeeds, this returns false, and the temporary file will
- have disappeared. If it fails, the temporary file will probably still exist,
- but will be deleted when this object is destroyed.
- */
- bool overwriteTargetFileWithTemporary() const;
-
- /** Attempts to delete the temporary file, if it exists.
- @returns true if the file is successfully deleted (or if it didn't exist).
- */
- bool deleteTemporaryFile() const;
-
-
-private:
- //==============================================================================
- const File temporaryFile, targetFile;
-};
-
-} // beast
-
-#endif // BEAST_TEMPORARYFILE_H_INCLUDED
diff --git a/src/beast/beast/module/core/logging/Logger.cpp b/src/beast/beast/module/core/logging/Logger.cpp
deleted file mode 100644
index 317f82698a..0000000000
--- a/src/beast/beast/module/core/logging/Logger.cpp
+++ /dev/null
@@ -1,63 +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
-{
-
-Logger::Logger() {}
-
-Logger::~Logger()
-{
- // You're deleting this logger while it's still being used!
- // Always call Logger::setCurrentLogger (nullptr) before deleting the active logger.
- bassert (currentLogger != this);
-}
-
-Logger* Logger::currentLogger = nullptr;
-
-void Logger::setCurrentLogger (Logger* const newLogger) noexcept { currentLogger = newLogger; }
-Logger* Logger::getCurrentLogger() noexcept { return currentLogger; }
-
-void Logger::writeToLog (const String& message)
-{
- if (currentLogger != nullptr)
- currentLogger->logMessage (message);
- else
- outputDebugString (message);
-}
-
-#if BEAST_LOG_ASSERTIONS || BEAST_DEBUG
-void logAssertion (const char* const filename, const int lineNum)
-{
- String m ("BEAST Assertion failure in ");
- m << File::createFileWithoutCheckingPath (filename).getFileName() << ':' << lineNum;
-
- #if BEAST_LOG_ASSERTIONS
- Logger::writeToLog (m);
- #else
- BDBG (m);
- #endif
-}
-#endif
-
-} // beast
diff --git a/src/beast/beast/module/core/logging/Logger.h b/src/beast/beast/module/core/logging/Logger.h
index 73aab2694a..cff7b91ae3 100644
--- a/src/beast/beast/module/core/logging/Logger.h
+++ b/src/beast/beast/module/core/logging/Logger.h
@@ -29,66 +29,7 @@
namespace beast
{
-//==============================================================================
-/**
- Acts as an application-wide logging class.
-
- A subclass of Logger can be created and passed into the Logger::setCurrentLogger
- method and this will then be used by all calls to writeToLog.
-
- The logger class also contains methods for writing messages to the debugger's
- output stream.
-*/
-class Logger
-{
-public:
- //==============================================================================
- /** Destructor. */
- virtual ~Logger();
-
- //==============================================================================
- /** Sets the current logging class to use.
-
- Note that the object passed in will not be owned or deleted by the logger, so
- 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 setCurrentLogger (Logger* newLogger) noexcept;
-
- /** Returns the current logger, or nullptr if none has been set. */
- static Logger* getCurrentLogger() noexcept;
-
- /** Writes a string to the current logger.
-
- This will pass the string to the logger's logMessage() method if a logger
- has been set.
-
- @see logMessage
- */
- static void writeToLog (const String& message);
-
-
- //==============================================================================
- /** Writes a message to the standard error stream.
-
- 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 outputDebugString (const String& text);
-
-
-protected:
- //==============================================================================
- Logger();
-
- /** This is overloaded by subclasses to implement custom logging behaviour.
- @see setCurrentLogger
- */
- virtual void logMessage (const String& message) = 0;
-
-private:
- static Logger* currentLogger;
-};
+void outputDebugString (std::string const& text);
} // beast
diff --git a/src/beast/beast/module/core/maths/Math.h b/src/beast/beast/module/core/maths/Math.h
deleted file mode 100644
index 0365c44331..0000000000
--- a/src/beast/beast/module/core/maths/Math.h
+++ /dev/null
@@ -1,89 +0,0 @@
-//------------------------------------------------------------------------------
-/*
- This file is part of Beast: https://github.com/vinniefalco/Beast
- Copyright 2013, Vinnie Falco
-
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies.
-
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-*/
-//==============================================================================
-
-#ifndef BEAST_MATH_H_INCLUDED
-#define BEAST_MATH_H_INCLUDED
-
-namespace beast
-{
-
-//
-// Miscellaneous mathematical calculations
-//
-
-// Calculate the bin for a value given the bin size.
-// This correctly handles negative numbers. For example
-// if value == -1 then calc_bin returns -1.
-template
-inline Ty calc_bin (Ty value, int size)
-{
- if (value >= 0)
- return value / size;
- else
- return (value - size + 1) / size;
-}
-
-// Given a number and a bin size, this returns the first
-// corresponding value of the bin associated with the given number.
-// It correctly handles negative numbers. For example,
-// if value == -1 then calc_bin always returns -size
-template
-inline Ty calc_bin_start (Ty value, int size)
-{
- return calc_bin (value, size) * size;
-}
-
-template
-inline T pi () noexcept
-{
- return 3.14159265358979;
-}
-
-template
-inline T twoPi () noexcept
-{
- return 6.28318530717958;
-}
-
-template
-inline T oneOverTwoPi () noexcept
-{
- return 0.1591549430918955;
-}
-
-template
-inline T degreesToRadians (U degrees)
-{
- return T (degrees * 0.0174532925199433);
-}
-
-template
-inline T radiansToDegrees (U radians)
-{
- T deg = T (radians * U (57.29577951308238));
-
- if (deg < 0)
- deg += 360;
-
- return deg;
-}
-
-} // beast
-
-#endif
diff --git a/src/beast/beast/module/core/maths/Range.h b/src/beast/beast/module/core/maths/Range.h
deleted file mode 100644
index f1a65f9f04..0000000000
--- a/src/beast/beast/module/core/maths/Range.h
+++ /dev/null
@@ -1,263 +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_RANGE_H_INCLUDED
-#define BEAST_RANGE_H_INCLUDED
-
-
-namespace beast
-{
-
-//==============================================================================
-/** A general-purpose range object, that simply represents any linear range with
- a start and end point.
-
- The templated parameter is expected to be a primitive integer or floating point
- type, though class types could also be used if they behave in a number-like way.
-*/
-template
-class Range
-{
-public:
- //==============================================================================
- /** Constructs an empty range. */
- Range() noexcept : start(), end()
- {
- }
-
- /** Constructs a range with given start and end values. */
- Range (const ValueType startValue, const ValueType endValue) noexcept
- : start (startValue), end (bmax (startValue, endValue))
- {
- }
-
- /** Constructs a copy of another range. */
- Range (const Range& other) noexcept
- : start (other.start), end (other.end)
- {
- }
-
- /** Copies another range object. */
- Range& operator= (Range other) noexcept
- {
- start = other.start;
- end = other.end;
- return *this;
- }
-
- /** Returns the range that lies between two positions (in either order). */
- static Range between (const ValueType position1, const ValueType position2) noexcept
- {
- return position1 < position2 ? Range (position1, position2)
- : Range (position2, position1);
- }
-
- /** Returns a range with the specified start position and a length of zero. */
- static Range emptyRange (const ValueType start) noexcept
- {
- return Range (start, start);
- }
-
- //==============================================================================
- /** Returns the start of the range. */
- inline ValueType getStart() const noexcept { return start; }
-
- /** Returns the length of the range. */
- inline ValueType getLength() const noexcept { return end - start; }
-
- /** Returns the end of the range. */
- inline ValueType getEnd() const noexcept { return end; }
-
- /** Returns true if the range has a length of zero. */
- inline bool isEmpty() const noexcept { return start == end; }
-
- //==============================================================================
- /** Changes the start position of the range, leaving the end position unchanged.
- If the new start position is higher than the current end of the range, the end point
- will be pushed along to equal it, leaving an empty range at the new position.
- */
- void setStart (const ValueType newStart) noexcept
- {
- start = newStart;
- if (end < newStart)
- end = newStart;
- }
-
- /** Returns a range with the same end as this one, but a different start.
- If the new start position is higher than the current end of the range, the end point
- will be pushed along to equal it, returning an empty range at the new position.
- */
- Range withStart (const ValueType newStart) const noexcept
- {
- return Range (newStart, bmax (newStart, end));
- }
-
- /** Returns a range with the same length as this one, but moved to have the given start position. */
- Range movedToStartAt (const ValueType newStart) const noexcept
- {
- return Range (newStart, end + (newStart - start));
- }
-
- /** Changes the end position of the range, leaving the start unchanged.
- If the new end position is below the current start of the range, the start point
- will be pushed back to equal the new end point.
- */
- void setEnd (const ValueType newEnd) noexcept
- {
- end = newEnd;
- if (newEnd < start)
- start = newEnd;
- }
-
- /** Returns a range with the same start position as this one, but a different end.
- If the new end position is below the current start of the range, the start point
- will be pushed back to equal the new end point.
- */
- Range withEnd (const ValueType newEnd) const noexcept
- {
- return Range (bmin (start, newEnd), newEnd);
- }
-
- /** Returns a range with the same length as this one, but moved to have the given end position. */
- Range movedToEndAt (const ValueType newEnd) const noexcept
- {
- return Range (start + (newEnd - end), newEnd);
- }
-
- /** Changes the length of the range.
- Lengths less than zero are treated as zero.
- */
- void setLength (const ValueType newLength) noexcept
- {
- end = start + bmax (ValueType(), newLength);
- }
-
- /** Returns a range with the same start as this one, but a different length.
- Lengths less than zero are treated as zero.
- */
- Range withLength (const ValueType newLength) const noexcept
- {
- return Range (start, start + newLength);
- }
-
- //==============================================================================
- /** Adds an amount to the start and end of the range. */
- inline Range operator+= (const ValueType amountToAdd) noexcept
- {
- start += amountToAdd;
- end += amountToAdd;
- return *this;
- }
-
- /** Subtracts an amount from the start and end of the range. */
- inline Range operator-= (const ValueType amountToSubtract) noexcept
- {
- start -= amountToSubtract;
- end -= amountToSubtract;
- return *this;
- }
-
- /** Returns a range that is equal to this one with an amount added to its
- start and end.
- */
- Range operator+ (const ValueType amountToAdd) const noexcept
- {
- return Range (start + amountToAdd, end + amountToAdd);
- }
-
- /** Returns a range that is equal to this one with the specified amount
- subtracted from its start and end. */
- Range operator- (const ValueType amountToSubtract) const noexcept
- {
- return Range (start - amountToSubtract, end - amountToSubtract);
- }
-
- bool operator== (Range other) const noexcept { return start == other.start && end == other.end; }
- bool operator!= (Range other) const noexcept { return start != other.start || end != other.end; }
-
- //==============================================================================
- /** Returns true if the given position lies inside this range. */
- bool contains (const ValueType position) const noexcept
- {
- return start <= position && position < end;
- }
-
- /** Returns the nearest value to the one supplied, which lies within the range. */
- ValueType clipValue (const ValueType value) const noexcept
- {
- return blimit (start, end, value);
- }
-
- /** Returns true if the given range lies entirely inside this range. */
- bool contains (Range other) const noexcept
- {
- return start <= other.start && end >= other.end;
- }
-
- /** Returns true if the given range intersects this one. */
- bool intersects (Range other) const noexcept
- {
- return other.start < end && start < other.end;
- }
-
- /** Returns the range that is the intersection of the two ranges, or an empty range
- with an undefined start position if they don't overlap. */
- Range getIntersectionWith (Range other) const noexcept
- {
- return Range (bmax (start, other.start),
- bmin (end, other.end));
- }
-
- /** Returns the smallest range that contains both this one and the other one. */
- Range getUnionWith (Range other) const noexcept
- {
- return Range (bmin (start, other.start),
- bmax (end, other.end));
- }
-
- /** Returns a given range, after moving it forwards or backwards to fit it
- within this range.
-
- If the supplied range has a greater length than this one, the return value
- will be this range.
-
- Otherwise, if the supplied range is smaller than this one, the return value
- will be the new range, shifted forwards or backwards so that it doesn't extend
- beyond this one, but keeping its original length.
- */
- Range constrainRange (Range rangeToConstrain) const noexcept
- {
- const ValueType otherLen = rangeToConstrain.getLength();
- return getLength() <= otherLen
- ? *this
- : rangeToConstrain.movedToStartAt (blimit (start, end - otherLen, rangeToConstrain.getStart()));
- }
-
-private:
- //==============================================================================
- ValueType start, end;
-};
-
-} // beast
-
-#endif // BEAST_RANGE_H_INCLUDED
diff --git a/src/beast/beast/module/core/memory/MemoryBlock.cpp b/src/beast/beast/module/core/memory/MemoryBlock.cpp
index 0c85889f7e..0e34d664da 100644
--- a/src/beast/beast/module/core/memory/MemoryBlock.cpp
+++ b/src/beast/beast/module/core/memory/MemoryBlock.cpp
@@ -21,6 +21,8 @@
*/
//==============================================================================
+#include
+
namespace beast
{
@@ -191,7 +193,7 @@ void MemoryBlock::insert (const void* const srcData, const size_t numBytes, size
if (numBytes > 0)
{
bassert (srcData != nullptr); // this must not be null!
- insertPosition = bmin (size, insertPosition);
+ insertPosition = std::min (size, insertPosition);
const size_t trailingDataSize = size - insertPosition;
setSize (size + numBytes, false);
@@ -277,7 +279,7 @@ int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const
while (numBits > 0 && (size_t) byte < size)
{
- const size_t bitsThisTime = bmin (numBits, 8 - offsetInByte);
+ const size_t bitsThisTime = std::min (numBits, 8 - offsetInByte);
const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
@@ -299,7 +301,7 @@ void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int b
while (numBits > 0 && (size_t) byte < size)
{
- const size_t bitsThisTime = bmin (numBits, 8 - offsetInByte);
+ const size_t bitsThisTime = std::min (numBits, 8 - offsetInByte);
const std::uint32_t tempMask = (mask << offsetInByte) | ~((((std::uint32_t) 0xffffffff) >> offsetInByte) << offsetInByte);
const std::uint32_t tempBits = (std::uint32_t) bitsToSet << offsetInByte;
diff --git a/src/beast/beast/module/core/misc/WindowsRegistry.h b/src/beast/beast/module/core/misc/WindowsRegistry.h
deleted file mode 100644
index 4e4f376489..0000000000
--- a/src/beast/beast/module/core/misc/WindowsRegistry.h
+++ /dev/null
@@ -1,120 +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_WINDOWSREGISTRY_H_INCLUDED
-#define BEAST_WINDOWSREGISTRY_H_INCLUDED
-
-namespace beast
-{
-
-#if BEAST_WINDOWS || DOXYGEN
-
-/**
- Contains some static helper functions for manipulating the MS Windows registry
- (Only available on Windows, of course!)
-*/
-namespace WindowsRegistry
-{
- //==============================================================================
- /** Returns a string from the registry.
- The path is a string for the entire path of a value in the registry,
- e.g. "HKEY_CURRENT_USER\Software\foo\bar"
- */
- String getValue (const String& regValuePath,
- const String& defaultValue = String::empty);
-
- /** Returns a string from the WOW64 registry.
- The path is a string for the entire path of a value in the registry,
- e.g. "HKEY_CURRENT_USER\Software\foo\bar"
- */
- String getValueWow64 (const String& regValuePath,
- const String& defaultValue = String::empty);
-
- /** Reads a binary block from the registry.
- The path is a string for the entire path of a value in the registry,
- e.g. "HKEY_CURRENT_USER\Software\foo\bar"
- @returns a DWORD indicating the type of the key.
- */
- 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.
- */
- bool setValue (const String& regValuePath, const String& value);
-
- /** Sets a registry value as a DWORD.
- This will take care of creating any groups needed to get to the given registry value.
- */
- 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.
- */
- 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.
- */
- bool setValue (const String& regValuePath, const MemoryBlock& value);
-
- /** Returns true if the given value exists in the registry. */
- bool valueExists (const String& regValuePath);
-
- /** Returns true if the given value exists in the registry. */
- bool valueExistsWow64 (const String& regValuePath);
-
- /** Deletes a registry value. */
- void deleteValue (const String& regValuePath);
-
- /** Deletes a registry key (which is registry-talk for 'folder'). */
- void deleteKey (const String& regKeyPath);
-
- /** Creates a file association in the registry.
-
- This lets you set the executable that should be launched by a given file extension.
- @param fileExtension the file extension to associate, including the
- initial dot, e.g. ".txt"
- @param symbolicDescription a space-free short token to identify the file type
- @param fullDescription a human-readable description of the file type
- @param targetExecutable the executable that should be launched
- @param iconResourceNumber the icon that gets displayed for the file type will be
- found by looking up this resource number in the
- executable. Pass 0 here to not use an icon
- @param registerForCurrentUserOnly if false, this will try to register the association
- for all users (you might not have permission to do this
- unless running in an installer). If true, it will register the
- association in HKEY_CURRENT_USER.
- */
- bool registerFileAssociation (const String& fileExtension,
- const String& symbolicDescription,
- const String& fullDescription,
- const File& targetExecutable,
- int iconResourceNumber,
- bool registerForCurrentUserOnly);
-};
-
-#endif
-
-} // beast
-
-#endif // BEAST_WINDOWSREGISTRY_H_INCLUDED
diff --git a/src/beast/beast/module/core/native/BasicNativeHeaders.h b/src/beast/beast/module/core/native/BasicNativeHeaders.h
index b3f42dcba0..1a727a4105 100644
--- a/src/beast/beast/module/core/native/BasicNativeHeaders.h
+++ b/src/beast/beast/module/core/native/BasicNativeHeaders.h
@@ -149,18 +149,6 @@
#endif
#endif
- /* Used with DynamicLibrary to simplify importing functions from a win32 DLL.
-
- dll: the DynamicLibrary object
- functionName: function to import
- localFunctionName: name you want to use to actually call it (must be different)
- returnType: the return type
- params: list of params (bracketed)
- */
- #define BEAST_LOAD_WINAPI_FUNCTION(dll, functionName, localFunctionName, returnType, params) \
- typedef returnType (WINAPI *type##localFunctionName) params; \
- type##localFunctionName localFunctionName = (type##localFunctionName) dll.getFunction (#functionName);
-
//==============================================================================
#elif BEAST_LINUX || BEAST_BSD
#include
diff --git a/src/beast/beast/module/core/native/bsd_Files.cpp b/src/beast/beast/module/core/native/bsd_Files.cpp
index e0eac389ef..0680925ff1 100644
--- a/src/beast/beast/module/core/native/bsd_Files.cpp
+++ b/src/beast/beast/module/core/native/bsd_Files.cpp
@@ -55,85 +55,19 @@ bool File::copyInternal (const File& dest) const
return false;
}
-void File::findFileSystemRoots (Array& destArray)
-{
- destArray.add (File ("/"));
-}
-
-//==============================================================================
-bool File::isOnCDRomDrive() const
-{
- struct statfs buf;
-
- return statfs (getFullPathName().toUTF8(), &buf) == 0
- && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
-}
-
-bool File::isOnHardDisk() const
-{
- struct statfs buf;
-
- if (statfs (getFullPathName().toUTF8(), &buf) == 0)
- {
- switch (buf.f_type)
- {
- case U_ISOFS_SUPER_MAGIC: // CD-ROM
- case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
- case U_NFS_SUPER_MAGIC: // Network NFS
- case U_SMB_SUPER_MAGIC: // Network Samba
- return false;
-
- default:
- // Assume anything else is a hard-disk (but note it could
- // be a RAM disk. There isn't a good way of determining
- // this for sure)
- return true;
- }
- }
-
- // Assume so if this fails for some reason
- return true;
-}
-
-bool File::isOnRemovableDrive() const
-{
- bassertfalse; // XXX not implemented for FreeBSD!
- return false;
-}
-
-bool File::isHidden() const
-{
- return getFileName().startsWithChar ('.');
-}
-
-//==============================================================================
-namespace
-{
- File beast_readlink (const String& file, const File& defaultFile)
- {
- const size_t size = 8192;
- HeapBlock buffer;
- buffer.malloc (size + 4);
-
- const size_t numBytes = readlink (file.toUTF8(), buffer, size);
-
- if (numBytes > 0 && numBytes <= size)
- return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
-
- return defaultFile;
- }
-}
-
-File File::getLinkedTarget() const
-{
- return beast_readlink (getFullPathName().toUTF8(), *this);
-}
-
//==============================================================================
static File resolveXDGFolder (const char* const type, const char* const fallbackFolder)
{
+ File userDirs ("~/.config/user-dirs.dirs");
StringArray confLines;
- File ("~/.config/user-dirs.dirs").readLines (confLines);
+
+ if (userDirs.existsAsFile())
+ {
+ FileInputStream in (userDirs);
+
+ if (in.openedOk())
+ confLines.addLines (in.readEntireStreamAsString());
+ }
for (int i = 0; i < confLines.size(); ++i)
{
@@ -199,18 +133,6 @@ File File::getSpecialLocation (const SpecialLocationType type)
return tmp;
}
- case invokedExecutableFile:
- if (beast_argv != nullptr && beast_argc > 0)
- return File (CharPointer_UTF8 (beast_argv[0]));
- // deliberate fall-through...
-
- case currentExecutableFile:
- case currentApplicationFile:
- return beast_getExecutableFile();
-
- case hostApplicationPath:
- return beast_readlink ("/proc/self/exe", beast_getExecutableFile());
-
default:
bassertfalse; // unknown type?
break;
@@ -219,30 +141,6 @@ File File::getSpecialLocation (const SpecialLocationType type)
return File::nonexistent ();
}
-//==============================================================================
-String File::getVersion() const
-{
- return String::empty; // xxx not yet implemented
-}
-
-//==============================================================================
-bool File::moveToTrash() const
-{
- if (! exists())
- return true;
-
- File trashCan ("~/.Trash");
-
- if (! trashCan.isDirectory())
- trashCan = "~/.local/share/Trash/files";
-
- if (! trashCan.isDirectory())
- return false;
-
- return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
- getFileExtension()));
-}
-
//==============================================================================
class DirectoryIterator::NativeIterator::Pimpl
{
@@ -319,59 +217,4 @@ bool DirectoryIterator::NativeIterator::next (String& filenameFound,
return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
}
-
-//==============================================================================
-static bool isFileExecutable (const String& filename)
-{
- beast_statStruct info;
-
- return beast_stat (filename, info)
- && S_ISREG (info.st_mode)
- && access (filename.toUTF8(), X_OK) == 0;
-}
-
-bool Process::openDocument (const String& fileName, const String& parameters)
-{
- String cmdString (fileName.replace (" ", "\\ ",false));
- cmdString << " " << parameters;
-
- if ( cmdString.startsWithIgnoreCase ("file:")
- || File::createFileWithoutCheckingPath (fileName).isDirectory()
- || ! isFileExecutable (fileName))
- {
- // create a command that tries to launch a bunch of likely browsers
- const char* const browserNames[] = { "xdg-open", "firefox", "seamonkey",
- "chrome", "opera", "konqueror" };
- StringArray cmdLines;
-
- for (int i = 0; i < numElementsInArray (browserNames); ++i)
- cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
-
- cmdString = cmdLines.joinIntoString (" || ");
- }
-
- const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
-
- const int cpid = fork();
-
- if (cpid == 0)
- {
- setsid();
-
- // Child process
- execve (argv[0], (char**) argv, environ);
- exit (0);
- }
-
- return cpid >= 0;
-}
-
-void File::revealToUser() const
-{
- if (isDirectory())
- startAsProcess();
- else if (getParentDirectory().exists())
- getParentDirectory().startAsProcess();
-}
-
} // beast
diff --git a/src/beast/beast/module/core/native/bsd_SystemStats.cpp b/src/beast/beast/module/core/native/bsd_SystemStats.cpp
index f8fc7656c5..2886e9ed3d 100644
--- a/src/beast/beast/module/core/native/bsd_SystemStats.cpp
+++ b/src/beast/beast/module/core/native/bsd_SystemStats.cpp
@@ -19,277 +19,22 @@
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
-//==============================================================================
-
-// sysinfo() from sysinfo-bsd
-// https://code.google.com/p/sysinfo-bsd/
-/*
- * Copyright (C) 2010 Kostas Petrikas, All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer
- * in this position and unchanged.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name(s) of the author(s) may not be used to endorse or promote
- * products derived from this software without specific prior written
- * permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-namespace beast
-{
-
-#define SI_LOAD_SHIFT 16
-struct sysinfo {
- long uptime; /* Seconds since boot */
- unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
- unsigned long totalram; /* Total usable main memory size */
- unsigned long freeram; /* Available memory size */
- unsigned long sharedram; /* Amount of shared memory */
- unsigned long bufferram; /* Memory used by buffers */
- unsigned long totalswap; /* Total swap space size */
- unsigned long freeswap; /* swap space still available */
- unsigned short procs; /* Number of current processes */
- unsigned short pad; /* leaving this for linux compatability */
- unsigned long totalhigh; /* Total high memory size */
- unsigned long freehigh; /* Available high memory size */
- unsigned int mem_unit; /* Memory unit size in bytes */
- char _f[20-2*sizeof(long)-sizeof(int)]; /* leaving this for linux compatability */
-};
-
-#define NLOADS 3
-#define UNIT_S 1024 /*Kb*/
-#define R_IGNORE -1
-
-/*the macros*/
-#define R_ERROR(_EC) {if(_EC > R_IGNORE)errno = _EC; return -1;}
-#define GETSYSCTL(name, var) getsysctl((char*)name, &(var), sizeof(var))
-#define PAGE_2_UNIT(_PAGE) (((double)_PAGE * page_s) / UNIT_S)
-
-/*sysctl wrapper*/
-static int getsysctl(char *name, void *ptr, size_t len){
- size_t nlen = len;
- if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1)
- return -1;
-
- if (nlen != len)
- return -1;
-
- return 0;
-}
-
-int sysinfo(struct sysinfo *info){
- kvm_t *kvmh;
- double load_avg[NLOADS];
- int page_s = getpagesize();
-
- if (info == NULL)
- R_ERROR(EFAULT);
-
- memset(info, 0, sizeof(struct sysinfo));
- info -> mem_unit = UNIT_S;
-
- /*kvm init*/
- if ((kvmh = kvm_open(NULL, "/dev/null", "/dev/null",
- O_RDONLY, "kvm_open")) == NULL)
- R_ERROR(0);
-
- /*load averages*/
- if (kvm_getloadavg(kvmh, load_avg, NLOADS) == -1)
- R_ERROR(0);
-
- info -> loads[0] = (u_long)((float)load_avg[0] * USHRT_MAX);
- info -> loads[1] = (u_long)((float)load_avg[1] * USHRT_MAX);
- info -> loads[2] = (u_long)((float)load_avg[2] * USHRT_MAX);
-
- /*swap space*/
- struct kvm_swap k_swap;
-
- if (kvm_getswapinfo(kvmh, &k_swap, 1, 0) == -1)
- R_ERROR(0);
-
- info -> totalswap =
- (u_long)PAGE_2_UNIT(k_swap.ksw_total);
- info -> freeswap = info -> totalswap -
- (u_long)PAGE_2_UNIT(k_swap.ksw_used);
-
- /*processes*/
- int n_procs;
-
- if (kvm_getprocs(kvmh, KERN_PROC_ALL, 0, &n_procs) == NULL)
- R_ERROR(0);
-
- info -> procs = (u_short)n_procs;
-
- /*end of kvm session*/
- if (kvm_close(kvmh) == -1)
- R_ERROR(0);
-
- /*uptime*/
- struct timespec ts;
-
- if (clock_gettime(CLOCK_UPTIME, &ts) == -1)
- R_ERROR(R_IGNORE);
-
- info -> uptime = (long)ts.tv_sec;
-
- /*ram*/
- int total_pages,
- free_pages,
- active_pages,
- inactive_pages;
- u_long shmmax;
-
- if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages) == -1)
- R_ERROR(R_IGNORE);
- if (GETSYSCTL("vm.stats.vm.v_free_count", free_pages) == -1)
- R_ERROR(R_IGNORE);
- if (GETSYSCTL("vm.stats.vm.v_active_count", active_pages) == -1)
- R_ERROR(R_IGNORE);
- if (GETSYSCTL("vm.stats.vm.v_inactive_count", inactive_pages) == -1)
- R_ERROR(R_IGNORE);
- if (GETSYSCTL("kern.ipc.shmmax", shmmax) == -1)
- R_ERROR(R_IGNORE);
-
- info -> totalram = (u_long)PAGE_2_UNIT(total_pages);
- info -> freeram = (u_long)PAGE_2_UNIT(free_pages);
- info -> bufferram = (u_long)PAGE_2_UNIT(active_pages);
- info -> sharedram = shmmax / UNIT_S;
-
- /*high mem (todo)*/
- info -> totalhigh = 0; /*Does this supose to refer to HMA or reserved ram?*/
- info -> freehigh = 0;
-
- return 0;
-}
//==============================================================================
-void Logger::outputDebugString (const String& text)
+void outputDebugString (std::string const& text)
{
std::cerr << text << std::endl;
}
//==============================================================================
-SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
-{
- return FreeBSD;
-}
-
-String SystemStats::getOperatingSystemName()
-{
- return "FreeBSD";
-}
-
-bool SystemStats::isOperatingSystem64Bit()
-
-{
- #if BEAST_64BIT
- return true;
- #else
- //xxx not sure how to find this out?..
- return false;
- #endif
-}
-
-//==============================================================================
-namespace BSDStatsHelpers
-{
- String getDmesgInfo (const char* const key)
- {
- StringArray lines;
- File ("/var/run/dmesg.boot").readLines (lines);
-
- for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
- if (lines[i].startsWith (key))
- return lines[i].substring (strlen (key)).trim();
-
- return String::empty;
- }
-
-}
-
-String SystemStats::getCpuVendor()
-{
- return BSDStatsHelpers::getDmesgInfo (" Origin =").upToFirstOccurrenceOf (" ", false, false).unquoted();
-}
-
-int SystemStats::getCpuSpeedInMegaherz()
-{
- return roundToInt (BSDStatsHelpers::getDmesgInfo ("CPU:").fromLastOccurrenceOf ("(", false, false).upToFirstOccurrenceOf ("-MHz", false, false).getFloatValue());
-}
-
-int SystemStats::getMemorySizeInMegabytes()
-{
- struct sysinfo sysi;
-
- if (sysinfo (&sysi) == 0)
- return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
-
- return 0;
-}
-
-int SystemStats::getPageSize()
-{
- return sysconf (_SC_PAGESIZE);
-}
-
-//==============================================================================
-String SystemStats::getLogonName()
-{
- const char* user = getenv ("USER");
-
- if (user == nullptr)
- {
- struct passwd* const pw = getpwuid (getuid());
- if (pw != nullptr)
- user = pw->pw_name;
- }
-
- return CharPointer_UTF8 (user);
-}
-
-String SystemStats::getFullUserName()
-{
- return getLogonName();
-}
-
-String SystemStats::getComputerName()
+std::string SystemStats::getComputerName()
{
char name [256] = { 0 };
if (gethostname (name, sizeof (name) - 1) == 0)
return name;
- return String::empty;
-}
-
-//==============================================================================
-void CPUInformation::initialise() noexcept
-{
- const String features (BSDStatsHelpers::getDmesgInfo (" Features="));
- hasMMX = features.contains ("MMX");
- hasSSE = features.contains ("SSE");
- hasSSE2 = features.contains ("SSE2");
- const String features2 (BSDStatsHelpers::getDmesgInfo (" Features2="));
- hasSSE3 = features2.contains ("SSE3");
- const String amdfeatures2 (BSDStatsHelpers::getDmesgInfo (" AMD Features2="));
- has3DNow = amdfeatures2.contains ("3DNow!");
+ return std::string{};
}
//==============================================================================
@@ -319,13 +64,4 @@ double Time::getMillisecondCounterHiRes() noexcept
return getHighResolutionTicks() * 0.001;
}
-bool Time::setSystemTimeToThisTime() const
-{
- timeval t;
- t.tv_sec = millisSinceEpoch / 1000;
- t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
-
- return settimeofday (&t, 0) == 0;
-}
-
} // beast
diff --git a/src/beast/beast/module/core/native/bsd_Threads.cpp b/src/beast/beast/module/core/native/bsd_Threads.cpp
index 9f7226686e..4b53bf2997 100644
--- a/src/beast/beast/module/core/native/bsd_Threads.cpp
+++ b/src/beast/beast/module/core/native/bsd_Threads.cpp
@@ -23,33 +23,7 @@
namespace beast
{
-
-/*
- Note that a lot of methods that you'd expect to find in this file actually
- live in beast_posix_SharedCode.h!
-*/
-
//==============================================================================
-void Process::setPriority (const ProcessPriority prior)
-{
- const int policy = (prior <= NormalPriority) ? SCHED_OTHER : SCHED_RR;
- const int minp = sched_get_priority_min (policy);
- const int maxp = sched_get_priority_max (policy);
-
- struct sched_param param;
-
- switch (prior)
- {
- case LowPriority:
- case NormalPriority: param.sched_priority = 0; break;
- case HighPriority: param.sched_priority = minp + (maxp - minp) / 4; break;
- case RealtimePriority: param.sched_priority = minp + (3 * (maxp - minp) / 4); break;
- default: bassertfalse; break;
- }
-
- pthread_setschedparam (pthread_self(), policy, ¶m);
-}
-
bool beast_isRunningUnderDebugger()
{
// XXX not implemented for FreeBSD!
@@ -62,13 +36,4 @@ bool Process::isRunningUnderDebugger()
return beast_isRunningUnderDebugger();
}
-static void swapUserAndEffectiveUser()
-{
- (void) setreuid (geteuid(), getuid());
- (void) setregid (getegid(), getgid());
-}
-
-void Process::raisePrivilege() { if (geteuid() != 0 && getuid() == 0) swapUserAndEffectiveUser(); }
-void Process::lowerPrivilege() { if (geteuid() == 0 && getuid() != 0) swapUserAndEffectiveUser(); }
-
} // beast
diff --git a/src/beast/beast/module/core/native/linux_Files.cpp b/src/beast/beast/module/core/native/linux_Files.cpp
index c3311df117..62004fb58d 100644
--- a/src/beast/beast/module/core/native/linux_Files.cpp
+++ b/src/beast/beast/module/core/native/linux_Files.cpp
@@ -55,85 +55,19 @@ bool File::copyInternal (const File& dest) const
return false;
}
-void File::findFileSystemRoots (Array