The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

803 lines
30KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. //==============================================================================
  20. /*
  21. This file sets up some handy mathematical typdefs and functions.
  22. */
  23. //==============================================================================
  24. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  25. /** A platform-independent 8-bit signed integer type. */
  26. using int8 = signed char;
  27. /** A platform-independent 8-bit unsigned integer type. */
  28. using uint8 = unsigned char;
  29. /** A platform-independent 16-bit signed integer type. */
  30. using int16 = signed short;
  31. /** A platform-independent 16-bit unsigned integer type. */
  32. using uint16 = unsigned short;
  33. /** A platform-independent 32-bit signed integer type. */
  34. using int32 = signed int;
  35. /** A platform-independent 32-bit unsigned integer type. */
  36. using uint32 = unsigned int;
  37. #if JUCE_MSVC
  38. /** A platform-independent 64-bit integer type. */
  39. using int64 = __int64;
  40. /** A platform-independent 64-bit unsigned integer type. */
  41. using uint64 = unsigned __int64;
  42. #else
  43. /** A platform-independent 64-bit integer type. */
  44. using int64 = long long;
  45. /** A platform-independent 64-bit unsigned integer type. */
  46. using uint64 = unsigned long long;
  47. #endif
  48. #ifndef DOXYGEN
  49. /** A macro for creating 64-bit literals.
  50. Historically, this was needed to support portability with MSVC6, and is kept here
  51. so that old code will still compile, but nowadays every compiler will support the
  52. LL and ULL suffixes, so you should use those in preference to this macro.
  53. */
  54. #define literal64bit(longLiteral) (longLiteral##LL)
  55. #endif
  56. #if JUCE_64BIT
  57. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  58. using pointer_sized_int = int64;
  59. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  60. using pointer_sized_uint = uint64;
  61. #elif JUCE_MSVC
  62. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  63. using pointer_sized_int = _W64 int;
  64. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  65. using pointer_sized_uint = _W64 unsigned int;
  66. #else
  67. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  68. using pointer_sized_int = int;
  69. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  70. using pointer_sized_uint = unsigned int;
  71. #endif
  72. #if JUCE_WINDOWS && ! JUCE_MINGW
  73. using ssize_t = pointer_sized_int;
  74. #endif
  75. //==============================================================================
  76. /** Handy function for avoiding unused variables warning. */
  77. template <typename... Types>
  78. void ignoreUnused (Types&&...) noexcept {}
  79. /** Handy function for getting the number of elements in a simple const C array.
  80. E.g.
  81. @code
  82. static int myArray[] = { 1, 2, 3 };
  83. int numElements = numElementsInArray (myArray) // returns 3
  84. @endcode
  85. */
  86. template <typename Type, size_t N>
  87. constexpr int numElementsInArray (Type (&)[N]) noexcept { return N; }
  88. //==============================================================================
  89. // Some useful maths functions that aren't always present with all compilers and build settings.
  90. /** Using juce_hypot is easier than dealing with the different types of hypot function
  91. that are provided by the various platforms and compilers. */
  92. template <typename Type>
  93. Type juce_hypot (Type a, Type b) noexcept
  94. {
  95. #if JUCE_MSVC
  96. return static_cast<Type> (_hypot (a, b));
  97. #else
  98. return static_cast<Type> (hypot (a, b));
  99. #endif
  100. }
  101. #ifndef DOXYGEN
  102. template <>
  103. inline float juce_hypot (float a, float b) noexcept
  104. {
  105. #if JUCE_MSVC
  106. return _hypotf (a, b);
  107. #else
  108. return hypotf (a, b);
  109. #endif
  110. }
  111. #endif
  112. //==============================================================================
  113. /** Commonly used mathematical constants
  114. @tags{Core}
  115. */
  116. template <typename FloatType>
  117. struct MathConstants
  118. {
  119. /** A predefined value for Pi */
  120. static constexpr FloatType pi = static_cast<FloatType> (3.141592653589793238L);
  121. /** A predefined value for 2 * Pi */
  122. static constexpr FloatType twoPi = static_cast<FloatType> (2 * 3.141592653589793238L);
  123. /** A predefined value for Pi / 2 */
  124. static constexpr FloatType halfPi = static_cast<FloatType> (3.141592653589793238L / 2);
  125. /** A predefined value for Euler's number */
  126. static constexpr FloatType euler = static_cast<FloatType> (2.71828182845904523536L);
  127. /** A predefined value for sqrt (2) */
  128. static constexpr FloatType sqrt2 = static_cast<FloatType> (1.4142135623730950488L);
  129. };
  130. #ifndef DOXYGEN
  131. /** A double-precision constant for pi. */
  132. [[deprecated ("This is deprecated in favour of MathConstants<double>::pi.")]]
  133. const constexpr double double_Pi = MathConstants<double>::pi;
  134. /** A single-precision constant for pi. */
  135. [[deprecated ("This is deprecated in favour of MathConstants<float>::pi.")]]
  136. const constexpr float float_Pi = MathConstants<float>::pi;
  137. #endif
  138. /** Converts an angle in degrees to radians. */
  139. template <typename FloatType>
  140. constexpr FloatType degreesToRadians (FloatType degrees) noexcept { return degrees * (MathConstants<FloatType>::pi / FloatType (180)); }
  141. /** Converts an angle in radians to degrees. */
  142. template <typename FloatType>
  143. constexpr FloatType radiansToDegrees (FloatType radians) noexcept { return radians * (FloatType (180) / MathConstants<FloatType>::pi); }
  144. //==============================================================================
  145. /** The isfinite() method seems to vary between platforms, so this is a
  146. platform-independent function for it.
  147. */
  148. template <typename NumericType>
  149. bool juce_isfinite (NumericType value) noexcept
  150. {
  151. if constexpr (std::numeric_limits<NumericType>::has_infinity
  152. || std::numeric_limits<NumericType>::has_quiet_NaN
  153. || std::numeric_limits<NumericType>::has_signaling_NaN)
  154. {
  155. return std::isfinite (value);
  156. }
  157. else
  158. {
  159. ignoreUnused (value);
  160. return true;
  161. }
  162. }
  163. //==============================================================================
  164. /** Equivalent to operator==, but suppresses float-equality warnings.
  165. This allows code to be explicit about float-equality checks that are known to have the correct
  166. semantics.
  167. */
  168. template <typename Type>
  169. constexpr bool exactlyEqual (Type a, Type b)
  170. {
  171. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wfloat-equal")
  172. return a == b;
  173. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  174. }
  175. /** A class encapsulating both relative and absolute tolerances for use in floating-point comparisons.
  176. @see approximatelyEqual, absoluteTolerance, relativeTolerance
  177. @tags{Core}
  178. */
  179. template <typename Type>
  180. class Tolerance
  181. {
  182. public:
  183. Tolerance() = default;
  184. /** Returns a copy of this Tolerance object with a new absolute tolerance.
  185. If you just need a Tolerance object with an absolute tolerance, it might be worth using the
  186. absoluteTolerance() function.
  187. @see getAbsolute, absoluteTolerance
  188. */
  189. [[nodiscard]] Tolerance withAbsolute (Type newAbsolute)
  190. {
  191. return withMember (*this, &Tolerance::absolute, std::abs (newAbsolute));
  192. }
  193. /** Returns a copy of this Tolerance object with a new relative tolerance.
  194. If you just need a Tolerance object with a relative tolerance, it might be worth using the
  195. relativeTolerance() function.
  196. @see getRelative, relativeTolerance
  197. */
  198. [[nodiscard]] Tolerance withRelative (Type newRelative)
  199. {
  200. return withMember (*this, &Tolerance::relative, std::abs (newRelative));
  201. }
  202. [[nodiscard]] Type getAbsolute() const { return absolute; }
  203. [[nodiscard]] Type getRelative() const { return relative; }
  204. private:
  205. Type absolute{};
  206. Type relative{};
  207. };
  208. /** Returns a type deduced Tolerance object containing only an absolute tolerance.
  209. @see Tolerance::withAbsolute, approximatelyEqual
  210. */
  211. template <typename Type>
  212. static Tolerance<Type> absoluteTolerance (Type tolerance)
  213. {
  214. return Tolerance<Type>{}.withAbsolute (tolerance);
  215. }
  216. /** Returns a type deduced Tolerance object containing only a relative tolerance.
  217. @see Tolerance::withRelative, approximatelyEqual
  218. */
  219. template <typename Type>
  220. static Tolerance<Type> relativeTolerance (Type tolerance)
  221. {
  222. return Tolerance<Type>{}.withRelative (tolerance);
  223. }
  224. /** Returns true if the two floating-point numbers are approximately equal.
  225. If either a or b are not finite, returns exactlyEqual (a, b).
  226. The default absolute tolerance is equal to the minimum normal value. This ensures
  227. differences that are subnormal are always considered equal. It is highly recommend this
  228. value is reviewed depending on the calculation being carried out. In general specifying an
  229. absolute value is useful when considering values close to zero. For example you might
  230. expect sin (pi) to return 0, but what it actually returns is close to the error of the value pi.
  231. Therefore, in this example it might be better to set the absolute tolerance to sin (pi).
  232. The default relative tolerance is equal to the machine epsilon which is the difference between
  233. 1.0 and the next floating-point value that can be represented by Type. In most cases this value
  234. is probably reasonable. This value is multiplied by the largest absolute value of a and b so as
  235. to scale relatively according to the input parameters. For example, specifying a relative value
  236. of 0.05 will ensure values return equal if the difference between them is less than or equal to
  237. 5% of the larger of the two absolute values.
  238. @param a The first number to compare.
  239. @param b The second number to compare.
  240. @param tolerance An object that represents both absolute and relative tolerances
  241. when evaluating if a and b are equal.
  242. @see exactlyEqual
  243. */
  244. template <typename Type, std::enable_if_t<std::is_floating_point_v<Type>, int> = 0>
  245. constexpr bool approximatelyEqual (Type a, Type b,
  246. Tolerance<Type> tolerance = Tolerance<Type>{}
  247. .withAbsolute (std::numeric_limits<Type>::min())
  248. .withRelative (std::numeric_limits<Type>::epsilon()))
  249. {
  250. if (! (juce_isfinite (a) && juce_isfinite (b)))
  251. return exactlyEqual (a, b);
  252. const auto diff = std::abs (a - b);
  253. return diff <= tolerance.getAbsolute()
  254. || diff <= tolerance.getRelative() * std::max (std::abs (a), std::abs (b));
  255. }
  256. /** Special case for non-floating-point types that returns true if both are exactly equal. */
  257. template <typename Type, std::enable_if_t<! std::is_floating_point_v<Type>, int> = 0>
  258. constexpr bool approximatelyEqual (Type a, Type b)
  259. {
  260. return a == b;
  261. }
  262. //==============================================================================
  263. /** Returns the next representable value by FloatType in the direction of the largest representable value. */
  264. template <typename FloatType>
  265. FloatType nextFloatUp (FloatType value) noexcept
  266. {
  267. return std::nextafter (value, std::numeric_limits<FloatType>::max());
  268. }
  269. /** Returns the next representable value by FloatType in the direction of the lowest representable value. */
  270. template <typename FloatType>
  271. FloatType nextFloatDown (FloatType value) noexcept
  272. {
  273. return std::nextafter (value, std::numeric_limits<FloatType>::lowest());
  274. }
  275. //==============================================================================
  276. // Some indispensable min/max functions
  277. /** Returns the larger of two values. */
  278. template <typename Type>
  279. constexpr Type jmax (Type a, Type b) { return a < b ? b : a; }
  280. /** Returns the larger of three values. */
  281. template <typename Type>
  282. constexpr Type jmax (Type a, Type b, Type c) { return a < b ? (b < c ? c : b) : (a < c ? c : a); }
  283. /** Returns the larger of four values. */
  284. template <typename Type>
  285. constexpr Type jmax (Type a, Type b, Type c, Type d) { return jmax (a, jmax (b, c, d)); }
  286. /** Returns the smaller of two values. */
  287. template <typename Type>
  288. constexpr Type jmin (Type a, Type b) { return b < a ? b : a; }
  289. /** Returns the smaller of three values. */
  290. template <typename Type>
  291. constexpr Type jmin (Type a, Type b, Type c) { return b < a ? (c < b ? c : b) : (c < a ? c : a); }
  292. /** Returns the smaller of four values. */
  293. template <typename Type>
  294. constexpr Type jmin (Type a, Type b, Type c, Type d) { return jmin (a, jmin (b, c, d)); }
  295. /** Remaps a normalised value (between 0 and 1) to a target range.
  296. This effectively returns (targetRangeMin + value0To1 * (targetRangeMax - targetRangeMin)).
  297. */
  298. template <typename Type>
  299. constexpr Type jmap (Type value0To1, Type targetRangeMin, Type targetRangeMax)
  300. {
  301. return targetRangeMin + value0To1 * (targetRangeMax - targetRangeMin);
  302. }
  303. /** Remaps a value from a source range to a target range. */
  304. template <typename Type>
  305. Type jmap (Type sourceValue, Type sourceRangeMin, Type sourceRangeMax, Type targetRangeMin, Type targetRangeMax)
  306. {
  307. jassert (! approximatelyEqual (sourceRangeMax, sourceRangeMin)); // mapping from a range of zero will produce NaN!
  308. return targetRangeMin + ((targetRangeMax - targetRangeMin) * (sourceValue - sourceRangeMin)) / (sourceRangeMax - sourceRangeMin);
  309. }
  310. /** Remaps a normalised value (between 0 and 1) to a logarithmic target range.
  311. The entire target range must be greater than zero.
  312. @see mapFromLog10
  313. @code
  314. mapToLog10 (0.5, 0.4, 40.0) == 4.0
  315. @endcode
  316. */
  317. template <typename Type>
  318. Type mapToLog10 (Type value0To1, Type logRangeMin, Type logRangeMax)
  319. {
  320. jassert (logRangeMin > 0);
  321. jassert (logRangeMax > 0);
  322. auto logMin = std::log10 (logRangeMin);
  323. auto logMax = std::log10 (logRangeMax);
  324. return std::pow ((Type) 10.0, value0To1 * (logMax - logMin) + logMin);
  325. }
  326. /** Remaps a logarithmic value in a target range to a normalised value (between 0 and 1).
  327. The entire target range must be greater than zero.
  328. @see mapToLog10
  329. @code
  330. mapFromLog10 (4.0, 0.4, 40.0) == 0.5
  331. @endcode
  332. */
  333. template <typename Type>
  334. Type mapFromLog10 (Type valueInLogRange, Type logRangeMin, Type logRangeMax)
  335. {
  336. jassert (logRangeMin > 0);
  337. jassert (logRangeMax > 0);
  338. auto logMin = std::log10 (logRangeMin);
  339. auto logMax = std::log10 (logRangeMax);
  340. return (std::log10 (valueInLogRange) - logMin) / (logMax - logMin);
  341. }
  342. /** Scans an array of values, returning the minimum value that it contains. */
  343. template <typename Type, typename Size>
  344. Type findMinimum (const Type* data, Size numValues)
  345. {
  346. if (numValues <= 0)
  347. return Type (0);
  348. auto result = *data++;
  349. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  350. {
  351. auto v = *data++;
  352. if (v < result)
  353. result = v;
  354. }
  355. return result;
  356. }
  357. /** Scans an array of values, returning the maximum value that it contains. */
  358. template <typename Type, typename Size>
  359. Type findMaximum (const Type* values, Size numValues)
  360. {
  361. if (numValues <= 0)
  362. return Type (0);
  363. auto result = *values++;
  364. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  365. {
  366. auto v = *values++;
  367. if (result < v)
  368. result = v;
  369. }
  370. return result;
  371. }
  372. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  373. template <typename Type>
  374. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  375. {
  376. if (numValues <= 0)
  377. {
  378. lowest = Type (0);
  379. highest = Type (0);
  380. }
  381. else
  382. {
  383. auto mn = *values++;
  384. auto mx = mn;
  385. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  386. {
  387. auto v = *values++;
  388. if (mx < v) mx = v;
  389. if (v < mn) mn = v;
  390. }
  391. lowest = mn;
  392. highest = mx;
  393. }
  394. }
  395. //==============================================================================
  396. /** Constrains a value to keep it within a given range.
  397. This will check that the specified value lies between the lower and upper bounds
  398. specified, and if not, will return the nearest value that would be in-range. Effectively,
  399. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  400. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  401. the results will be unpredictable.
  402. @param lowerLimit the minimum value to return
  403. @param upperLimit the maximum value to return
  404. @param valueToConstrain the value to try to return
  405. @returns the closest value to valueToConstrain which lies between lowerLimit
  406. and upperLimit (inclusive)
  407. @see jmin, jmax, jmap
  408. */
  409. template <typename Type>
  410. Type jlimit (Type lowerLimit,
  411. Type upperLimit,
  412. Type valueToConstrain) noexcept
  413. {
  414. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  415. return valueToConstrain < lowerLimit ? lowerLimit
  416. : (upperLimit < valueToConstrain ? upperLimit
  417. : valueToConstrain);
  418. }
  419. /** Returns true if a value is at least zero, and also below a specified upper limit.
  420. This is basically a quicker way to write:
  421. @code valueToTest >= 0 && valueToTest < upperLimit
  422. @endcode
  423. */
  424. template <typename Type1, typename Type2>
  425. bool isPositiveAndBelow (Type1 valueToTest, Type2 upperLimit) noexcept
  426. {
  427. jassert (Type1() <= static_cast<Type1> (upperLimit)); // makes no sense to call this if the upper limit is itself below zero..
  428. return Type1() <= valueToTest && valueToTest < static_cast<Type1> (upperLimit);
  429. }
  430. template <typename Type>
  431. bool isPositiveAndBelow (int valueToTest, Type upperLimit) noexcept
  432. {
  433. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  434. return static_cast<unsigned int> (valueToTest) < static_cast<unsigned int> (upperLimit);
  435. }
  436. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  437. This is basically a quicker way to write:
  438. @code valueToTest >= 0 && valueToTest <= upperLimit
  439. @endcode
  440. */
  441. template <typename Type1, typename Type2>
  442. bool isPositiveAndNotGreaterThan (Type1 valueToTest, Type2 upperLimit) noexcept
  443. {
  444. jassert (Type1() <= static_cast<Type1> (upperLimit)); // makes no sense to call this if the upper limit is itself below zero..
  445. return Type1() <= valueToTest && valueToTest <= static_cast<Type1> (upperLimit);
  446. }
  447. template <typename Type>
  448. bool isPositiveAndNotGreaterThan (int valueToTest, Type upperLimit) noexcept
  449. {
  450. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  451. return static_cast<unsigned int> (valueToTest) <= static_cast<unsigned int> (upperLimit);
  452. }
  453. /** Computes the absolute difference between two values and returns true if it is less than or equal
  454. to a given tolerance, otherwise it returns false.
  455. */
  456. template <typename Type>
  457. bool isWithin (Type a, Type b, Type tolerance) noexcept
  458. {
  459. return std::abs (a - b) <= tolerance;
  460. }
  461. //==============================================================================
  462. #if JUCE_MSVC
  463. #pragma optimize ("t", off)
  464. #ifndef __INTEL_COMPILER
  465. #pragma float_control (precise, on, push)
  466. #endif
  467. #endif
  468. /** Fast floating-point-to-integer conversion.
  469. This is faster than using the normal c++ cast to convert a float to an int, and
  470. it will round the value to the nearest integer, rather than rounding it down
  471. like the normal cast does.
  472. Note that this routine gets its speed at the expense of some accuracy, and when
  473. rounding values whose floating point component is exactly 0.5, odd numbers and
  474. even numbers will be rounded up or down differently.
  475. */
  476. template <typename FloatType>
  477. int roundToInt (const FloatType value) noexcept
  478. {
  479. #ifdef __INTEL_COMPILER
  480. #pragma float_control (precise, on, push)
  481. #endif
  482. union { int asInt[2]; double asDouble; } n;
  483. n.asDouble = ((double) value) + 6755399441055744.0;
  484. #if JUCE_BIG_ENDIAN
  485. return n.asInt [1];
  486. #else
  487. return n.asInt [0];
  488. #endif
  489. }
  490. inline int roundToInt (int value) noexcept
  491. {
  492. return value;
  493. }
  494. #if JUCE_MSVC
  495. #ifndef __INTEL_COMPILER
  496. #pragma float_control (pop)
  497. #endif
  498. #pragma optimize ("", on) // resets optimisations to the project defaults
  499. #endif
  500. /** Fast floating-point-to-integer conversion.
  501. This is a slightly slower and slightly more accurate version of roundToInt(). It works
  502. fine for values above zero, but negative numbers are rounded the wrong way.
  503. */
  504. inline int roundToIntAccurate (double value) noexcept
  505. {
  506. #ifdef __INTEL_COMPILER
  507. #pragma float_control (pop)
  508. #endif
  509. return roundToInt (value + 1.5e-8);
  510. }
  511. //==============================================================================
  512. /** Truncates a positive floating-point number to an unsigned int.
  513. This is generally faster than static_cast<unsigned int> (std::floor (x))
  514. but it only works for positive numbers small enough to be represented as an
  515. unsigned int.
  516. */
  517. template <typename FloatType>
  518. unsigned int truncatePositiveToUnsignedInt (FloatType value) noexcept
  519. {
  520. jassert (value >= static_cast<FloatType> (0));
  521. jassert (static_cast<FloatType> (value)
  522. <= static_cast<FloatType> (std::numeric_limits<unsigned int>::max()));
  523. return static_cast<unsigned int> (value);
  524. }
  525. //==============================================================================
  526. /** Returns true if the specified integer is a power-of-two. */
  527. template <typename IntegerType>
  528. constexpr bool isPowerOfTwo (IntegerType value)
  529. {
  530. return (value & (value - 1)) == 0;
  531. }
  532. /** Returns the smallest power-of-two which is equal to or greater than the given integer. */
  533. inline int nextPowerOfTwo (int n) noexcept
  534. {
  535. --n;
  536. n |= (n >> 1);
  537. n |= (n >> 2);
  538. n |= (n >> 4);
  539. n |= (n >> 8);
  540. n |= (n >> 16);
  541. return n + 1;
  542. }
  543. /** Returns the index of the highest set bit in a (non-zero) number.
  544. So for n=3 this would return 1, for n=7 it returns 2, etc.
  545. An input value of 0 is illegal!
  546. */
  547. int findHighestSetBit (uint32 n) noexcept;
  548. /** Returns the number of bits in a 32-bit integer. */
  549. constexpr int countNumberOfBits (uint32 n) noexcept
  550. {
  551. n -= ((n >> 1) & 0x55555555);
  552. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  553. n = (((n >> 4) + n) & 0x0f0f0f0f);
  554. n += (n >> 8);
  555. n += (n >> 16);
  556. return (int) (n & 0x3f);
  557. }
  558. /** Returns the number of bits in a 64-bit integer. */
  559. constexpr int countNumberOfBits (uint64 n) noexcept
  560. {
  561. return countNumberOfBits ((uint32) n) + countNumberOfBits ((uint32) (n >> 32));
  562. }
  563. /** Performs a modulo operation, but can cope with the dividend being negative.
  564. The divisor must be greater than zero.
  565. */
  566. template <typename IntegerType>
  567. IntegerType negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
  568. {
  569. jassert (divisor > 0);
  570. dividend %= divisor;
  571. return (dividend < 0) ? (dividend + divisor) : dividend;
  572. }
  573. /** Returns the square of its argument. */
  574. template <typename NumericType>
  575. inline constexpr NumericType square (NumericType n) noexcept
  576. {
  577. return n * n;
  578. }
  579. //==============================================================================
  580. /** Writes a number of bits into a memory buffer at a given bit index.
  581. The buffer is treated as a sequence of 8-bit bytes, and the value is encoded in little-endian order,
  582. so for example if startBit = 10, and numBits = 11 then the lower 6 bits of the value would be written
  583. into bits 2-8 of targetBuffer[1], and the upper 5 bits of value into bits 0-5 of targetBuffer[2].
  584. @see readLittleEndianBitsInBuffer
  585. */
  586. void writeLittleEndianBitsInBuffer (void* targetBuffer, uint32 startBit, uint32 numBits, uint32 value) noexcept;
  587. /** Reads a number of bits from a buffer at a given bit index.
  588. The buffer is treated as a sequence of 8-bit bytes, and the value is encoded in little-endian order,
  589. so for example if startBit = 10, and numBits = 11 then the lower 6 bits of the result would be read
  590. from bits 2-8 of sourceBuffer[1], and the upper 5 bits of the result from bits 0-5 of sourceBuffer[2].
  591. @see writeLittleEndianBitsInBuffer
  592. */
  593. uint32 readLittleEndianBitsInBuffer (const void* sourceBuffer, uint32 startBit, uint32 numBits) noexcept;
  594. //==============================================================================
  595. #if JUCE_INTEL || DOXYGEN
  596. /** This macro can be applied to a float variable to check whether it contains a denormalised
  597. value, and to normalise it if necessary.
  598. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  599. */
  600. #define JUCE_UNDENORMALISE(x) { (x) += 0.1f; (x) -= 0.1f; }
  601. #else
  602. #define JUCE_UNDENORMALISE(x)
  603. #endif
  604. //==============================================================================
  605. /** This namespace contains a few template classes for helping work out class type variations.
  606. */
  607. namespace TypeHelpers
  608. {
  609. /** The ParameterType struct is used to find the best type to use when passing some kind
  610. of object as a parameter.
  611. Of course, this is only likely to be useful in certain esoteric template situations.
  612. E.g. "myFunction (typename TypeHelpers::ParameterType<int>::type, typename TypeHelpers::ParameterType<MyObject>::type)"
  613. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  614. pass-by-value, but passing objects as a const reference, to avoid copying.
  615. @tags{Core}
  616. */
  617. template <typename Type> struct ParameterType { using type = const Type&; };
  618. #ifndef DOXYGEN
  619. template <typename Type> struct ParameterType <Type&> { using type = Type&; };
  620. template <typename Type> struct ParameterType <Type*> { using type = Type*; };
  621. template <> struct ParameterType <char> { using type = char; };
  622. template <> struct ParameterType <unsigned char> { using type = unsigned char; };
  623. template <> struct ParameterType <short> { using type = short; };
  624. template <> struct ParameterType <unsigned short> { using type = unsigned short; };
  625. template <> struct ParameterType <int> { using type = int; };
  626. template <> struct ParameterType <unsigned int> { using type = unsigned int; };
  627. template <> struct ParameterType <long> { using type = long; };
  628. template <> struct ParameterType <unsigned long> { using type = unsigned long; };
  629. template <> struct ParameterType <int64> { using type = int64; };
  630. template <> struct ParameterType <uint64> { using type = uint64; };
  631. template <> struct ParameterType <bool> { using type = bool; };
  632. template <> struct ParameterType <float> { using type = float; };
  633. template <> struct ParameterType <double> { using type = double; };
  634. #endif
  635. /** These templates are designed to take a type, and if it's a double, they return a double
  636. type; for anything else, they return a float type.
  637. @tags{Core}
  638. */
  639. template <typename Type>
  640. using SmallestFloatType = std::conditional_t<std::is_same_v<Type, double>, double, float>;
  641. /** These templates are designed to take an integer type, and return an unsigned int
  642. version with the same size.
  643. @tags{Core}
  644. */
  645. template <int bytes> struct UnsignedTypeWithSize {};
  646. #ifndef DOXYGEN
  647. template <> struct UnsignedTypeWithSize<1> { using type = uint8; };
  648. template <> struct UnsignedTypeWithSize<2> { using type = uint16; };
  649. template <> struct UnsignedTypeWithSize<4> { using type = uint32; };
  650. template <> struct UnsignedTypeWithSize<8> { using type = uint64; };
  651. #endif
  652. }
  653. //==============================================================================
  654. #ifndef DOXYGEN
  655. [[deprecated ("Use roundToInt instead.")]] inline int roundDoubleToInt (double value) noexcept { return roundToInt (value); }
  656. [[deprecated ("Use roundToInt instead.")]] inline int roundFloatToInt (float value) noexcept { return roundToInt (value); }
  657. [[deprecated ("Use std::abs() instead.")]] inline int64 abs64 (int64 n) noexcept { return std::abs (n); }
  658. #endif
  659. } // namespace juce