Audio plugin host https://kx.studio/carla
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.

393 lines
15KB

  1. /*
  2. * Carla misc utils based on Juce
  3. * Copyright (C) 2013 Raw Material Software Ltd.
  4. * Copyright (C) 2013-2015 Filipe Coelho <falktx@falktx.com>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any purpose with
  7. * or without fee is hereby granted, provided that the above copyright notice and this
  8. * permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  11. * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  12. * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  13. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  14. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  15. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #ifndef CARLA_JUCE_UTILS_HPP_INCLUDED
  18. #define CARLA_JUCE_UTILS_HPP_INCLUDED
  19. #define DISTRHO_LEAK_DETECTOR_HPP_INCLUDED
  20. #define DISTRHO_SCOPED_POINTER_HPP_INCLUDED
  21. #define DISTRHO_LEAK_DETECTOR CARLA_LEAK_DETECTOR
  22. #define DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR
  23. #include "CarlaUtils.hpp"
  24. #include <algorithm>
  25. /** A good old-fashioned C macro concatenation helper.
  26. This combines two items (which may themselves be macros) into a single string,
  27. avoiding the pitfalls of the ## macro operator.
  28. */
  29. #define CARLA_JOIN_MACRO_HELPER(a, b) a ## b
  30. #define CARLA_JOIN_MACRO(item1, item2) CARLA_JOIN_MACRO_HELPER(item1, item2)
  31. #ifdef DEBUG
  32. /** This macro lets you embed a leak-detecting object inside a class.
  33. To use it, simply declare a CARLA_LEAK_DETECTOR(YourClassName) inside a private section
  34. of the class declaration. E.g.
  35. @code
  36. class MyClass
  37. {
  38. public:
  39. MyClass();
  40. void blahBlah();
  41. private:
  42. CARLA_LEAK_DETECTOR(MyClass)
  43. };
  44. @endcode
  45. */
  46. # define CARLA_LEAK_DETECTOR(ClassName) \
  47. friend class ::LeakedObjectDetector<ClassName>; \
  48. static const char* getLeakedObjectClassName() noexcept { return #ClassName; } \
  49. ::LeakedObjectDetector<ClassName> CARLA_JOIN_MACRO(leakDetector_, ClassName);
  50. # define CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ClassName) \
  51. CARLA_DECLARE_NON_COPY_CLASS(ClassName) \
  52. CARLA_LEAK_DETECTOR(ClassName)
  53. #else
  54. /** Don't use leak detection on release builds. */
  55. # define CARLA_LEAK_DETECTOR(ClassName)
  56. # define CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ClassName) \
  57. CARLA_DECLARE_NON_COPY_CLASS(ClassName)
  58. #endif
  59. //=====================================================================================================================
  60. /**
  61. Embedding an instance of this class inside another class can be used as a low-overhead
  62. way of detecting leaked instances.
  63. This class keeps an internal static count of the number of instances that are
  64. active, so that when the app is shutdown and the static destructors are called,
  65. it can check whether there are any left-over instances that may have been leaked.
  66. To use it, use the CARLA_LEAK_DETECTOR macro as a simple way to put one in your
  67. class declaration.
  68. */
  69. template <class OwnerClass>
  70. class LeakedObjectDetector
  71. {
  72. public:
  73. //=================================================================================================================
  74. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  75. LeakedObjectDetector(const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  76. ~LeakedObjectDetector() noexcept
  77. {
  78. if (--(getCounter().numObjects) < 0)
  79. {
  80. /** If you hit this, then you've managed to delete more instances of this class than you've
  81. created.. That indicates that you're deleting some dangling pointers.
  82. Note that although this assertion will have been triggered during a destructor, it might
  83. not be this particular deletion that's at fault - the incorrect one may have happened
  84. at an earlier point in the program, and simply not been detected until now.
  85. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  86. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  87. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  88. */
  89. carla_stderr2("*** Dangling pointer deletion! Class: '%s', Count: %i", getLeakedObjectClassName(),
  90. getCounter().numObjects);
  91. }
  92. }
  93. private:
  94. //=================================================================================================================
  95. class LeakCounter
  96. {
  97. public:
  98. LeakCounter() noexcept
  99. : numObjects(0) {}
  100. ~LeakCounter() noexcept
  101. {
  102. if (numObjects > 0)
  103. {
  104. /** If you hit this, then you've leaked one or more objects of the type specified by
  105. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  106. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  107. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  108. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  109. */
  110. carla_stderr2("*** Leaked objects detected: %i instance(s) of class '%s'", numObjects,
  111. getLeakedObjectClassName());
  112. }
  113. }
  114. // this should be an atomic...
  115. volatile int numObjects;
  116. };
  117. static const char* getLeakedObjectClassName() noexcept
  118. {
  119. return OwnerClass::getLeakedObjectClassName();
  120. }
  121. static LeakCounter& getCounter() noexcept
  122. {
  123. static LeakCounter counter;
  124. return counter;
  125. }
  126. };
  127. //=====================================================================================================================
  128. /**
  129. This class holds a pointer which is automatically deleted when this object goes
  130. out of scope.
  131. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  132. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  133. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  134. created objects.
  135. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  136. to an object. If you use the assignment operator to assign a different object to a
  137. ScopedPointer, the old one will be automatically deleted.
  138. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  139. object to which it points during its lifetime. This means that making a copy of a const
  140. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  141. old one.
  142. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  143. can use the release() method.
  144. Something to note is the main difference between this class and the std::auto_ptr class,
  145. which is that ScopedPointer provides a cast-to-object operator, wheras std::auto_ptr
  146. requires that you always call get() to retrieve the pointer. The advantages of providing
  147. the cast is that you don't need to call get(), so can use the ScopedPointer in pretty much
  148. exactly the same way as a raw pointer. The disadvantage is that the compiler is free to
  149. use the cast in unexpected and sometimes dangerous ways - in particular, it becomes difficult
  150. to return a ScopedPointer as the result of a function. To avoid this causing errors,
  151. ScopedPointer contains an overloaded constructor that should cause a syntax error in these
  152. circumstances, but it does mean that instead of returning a ScopedPointer from a function,
  153. you'd need to return a raw pointer (or use a std::auto_ptr instead).
  154. */
  155. template<class ObjectType>
  156. class ScopedPointer
  157. {
  158. public:
  159. //=================================================================================================================
  160. /** Creates a ScopedPointer containing a null pointer. */
  161. ScopedPointer() noexcept
  162. : object(nullptr) {}
  163. /** Creates a ScopedPointer that owns the specified object. */
  164. ScopedPointer(ObjectType* const objectToTakePossessionOf) noexcept
  165. : object(objectToTakePossessionOf) {}
  166. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  167. Because a pointer can only belong to one ScopedPointer, this transfers
  168. the pointer from the other object to this one, and the other object is reset to
  169. be a null pointer.
  170. */
  171. ScopedPointer(ScopedPointer& objectToTransferFrom) noexcept
  172. : object(objectToTransferFrom.object)
  173. {
  174. objectToTransferFrom.object = nullptr;
  175. }
  176. /** Destructor.
  177. This will delete the object that this ScopedPointer currently refers to.
  178. */
  179. ~ScopedPointer()
  180. {
  181. delete object;
  182. }
  183. /** Changes this ScopedPointer to point to a new object.
  184. Because a pointer can only belong to one ScopedPointer, this transfers
  185. the pointer from the other object to this one, and the other object is reset to
  186. be a null pointer.
  187. If this ScopedPointer already points to an object, that object
  188. will first be deleted.
  189. */
  190. ScopedPointer& operator=(ScopedPointer& objectToTransferFrom)
  191. {
  192. if (this != objectToTransferFrom.getAddress())
  193. {
  194. // Two ScopedPointers should never be able to refer to the same object - if
  195. // this happens, you must have done something dodgy!
  196. CARLA_SAFE_ASSERT_RETURN(object == nullptr || object != objectToTransferFrom.object, *this);
  197. ObjectType* const oldObject = object;
  198. object = objectToTransferFrom.object;
  199. objectToTransferFrom.object = nullptr;
  200. delete oldObject;
  201. }
  202. return *this;
  203. }
  204. /** Changes this ScopedPointer to point to a new object.
  205. If this ScopedPointer already points to an object, that object
  206. will first be deleted.
  207. The pointer that you pass in may be a nullptr.
  208. */
  209. ScopedPointer& operator=(ObjectType* const newObjectToTakePossessionOf)
  210. {
  211. if (object != newObjectToTakePossessionOf)
  212. {
  213. ObjectType* const oldObject = object;
  214. object = newObjectToTakePossessionOf;
  215. delete oldObject;
  216. }
  217. return *this;
  218. }
  219. //=================================================================================================================
  220. /** Returns the object that this ScopedPointer refers to. */
  221. operator ObjectType*() const noexcept { return object; }
  222. /** Returns the object that this ScopedPointer refers to. */
  223. ObjectType* get() const noexcept { return object; }
  224. /** Returns the object that this ScopedPointer refers to. */
  225. ObjectType& operator*() const noexcept { return *object; }
  226. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  227. ObjectType* operator->() const noexcept { return object; }
  228. //=================================================================================================================
  229. /** Removes the current object from this ScopedPointer without deleting it.
  230. This will return the current object, and set the ScopedPointer to a null pointer.
  231. */
  232. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  233. //=================================================================================================================
  234. /** Swaps this object with that of another ScopedPointer.
  235. The two objects simply exchange their pointers.
  236. */
  237. void swapWith(ScopedPointer<ObjectType>& other) noexcept
  238. {
  239. // Two ScopedPointers should never be able to refer to the same object - if
  240. // this happens, you must have done something dodgy!
  241. CARLA_SAFE_ASSERT_RETURN(object != other.object || this == other.getAddress() || object == nullptr,);
  242. std::swap(object, other.object);
  243. }
  244. private:
  245. //=================================================================================================================
  246. ObjectType* object;
  247. // (Required as an alternative to the overloaded & operator).
  248. const ScopedPointer* getAddress() const noexcept { return this; }
  249. #ifdef CARLA_PROPER_CPP11_SUPPORT
  250. ScopedPointer(const ScopedPointer&) = delete;
  251. ScopedPointer& operator=(const ScopedPointer&) = delete;
  252. #else
  253. ScopedPointer(const ScopedPointer&);
  254. ScopedPointer& operator=(const ScopedPointer&);
  255. #endif
  256. };
  257. //=====================================================================================================================
  258. /** Compares a ScopedPointer with another pointer.
  259. This can be handy for checking whether this is a null pointer.
  260. */
  261. template<class ObjectType>
  262. bool operator==(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  263. {
  264. return static_cast<ObjectType*>(pointer1) == pointer2;
  265. }
  266. /** Compares a ScopedPointer with another pointer.
  267. This can be handy for checking whether this is a null pointer.
  268. */
  269. template<class ObjectType>
  270. bool operator!=(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  271. {
  272. return static_cast<ObjectType*>(pointer1) != pointer2;
  273. }
  274. //=====================================================================================================================
  275. /**
  276. Helper class providing an RAII-based mechanism for temporarily setting and
  277. then re-setting a value.
  278. E.g. @code
  279. int x = 1;
  280. {
  281. ScopedValueSetter setter (x, 2);
  282. // x is now 2
  283. }
  284. // x is now 1 again
  285. {
  286. ScopedValueSetter setter (x, 3, 4);
  287. // x is now 3
  288. }
  289. // x is now 4
  290. @endcode
  291. */
  292. template <typename ValueType>
  293. class ScopedValueSetter
  294. {
  295. public:
  296. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  297. given new value, and will then reset it to its original value when this object is deleted.
  298. Must be used only for 'noexcept' compatible types.
  299. */
  300. ScopedValueSetter(ValueType& valueToSet, ValueType newValue) noexcept
  301. : value(valueToSet),
  302. originalValue(valueToSet)
  303. {
  304. valueToSet = newValue;
  305. }
  306. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  307. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  308. */
  309. ScopedValueSetter(ValueType& valueToSet, ValueType newValue, ValueType valueWhenDeleted) noexcept
  310. : value(valueToSet),
  311. originalValue(valueWhenDeleted)
  312. {
  313. valueToSet = newValue;
  314. }
  315. ~ScopedValueSetter() noexcept
  316. {
  317. value = originalValue;
  318. }
  319. private:
  320. //=================================================================================================================
  321. ValueType& value;
  322. const ValueType originalValue;
  323. CARLA_DECLARE_NON_COPY_CLASS(ScopedValueSetter)
  324. CARLA_PREVENT_HEAP_ALLOCATION
  325. };
  326. //=====================================================================================================================
  327. #endif // CARLA_JUCE_UTILS_HPP_INCLUDED