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.

343 lines
14KB

  1. /*
  2. * Carla misc utils imported from Juce source code
  3. * Copyright (c) 2013 Raw Material Software Ltd.
  4. * Copyright (C) 2013 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. #include "CarlaUtils.hpp"
  20. #include <algorithm>
  21. #define CARLA_DECLARE_NON_COPYABLE(ClassName) \
  22. private: \
  23. ClassName(ClassName&); \
  24. ClassName(const ClassName&); \
  25. ClassName& operator=(const ClassName&);
  26. /** This is a shorthand way of writing both a CARLA_DECLARE_NON_COPYABLE and
  27. CARLA_LEAK_DETECTOR macro for a class.
  28. */
  29. #define CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ClassName) \
  30. CARLA_DECLARE_NON_COPYABLE(ClassName) \
  31. CARLA_LEAK_DETECTOR(ClassName)
  32. /** This macro can be added to class definitions to disable the use of new/delete to
  33. allocate the object on the heap, forcing it to only be used as a stack or member variable.
  34. */
  35. #define CARLA_PREVENT_HEAP_ALLOCATION \
  36. private: \
  37. static void* operator new (size_t); \
  38. static void operator delete (void*);
  39. /** A good old-fashioned C macro concatenation helper.
  40. This combines two items (which may themselves be macros) into a single string,
  41. avoiding the pitfalls of the ## macro operator.
  42. */
  43. #define CARLA_JOIN_MACRO_HELPER(a, b) a ## b
  44. #define CARLA_JOIN_MACRO(item1, item2) CARLA_JOIN_MACRO_HELPER (item1, item2)
  45. //==============================================================================
  46. /**
  47. Embedding an instance of this class inside another class can be used as a low-overhead
  48. way of detecting leaked instances.
  49. This class keeps an internal static count of the number of instances that are
  50. active, so that when the app is shutdown and the static destructors are called,
  51. it can check whether there are any left-over instances that may have been leaked.
  52. To use it, use the CARLA_LEAK_DETECTOR macro as a simple way to put one in your
  53. class declaration. Have a look through the carla codebase for examples, it's used
  54. in most of the classes.
  55. */
  56. template <class OwnerClass>
  57. class LeakedObjectDetector
  58. {
  59. public:
  60. //==============================================================================
  61. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  62. LeakedObjectDetector(const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  63. ~LeakedObjectDetector()
  64. {
  65. if (--(getCounter().numObjects) < 0)
  66. {
  67. carla_stderr("*** Dangling pointer deletion! Class: '%s'", getLeakedObjectClassName());
  68. /** If you hit this, then you've managed to delete more instances of this class than you've
  69. created.. That indicates that you're deleting some dangling pointers.
  70. Note that although this assertion will have been triggered during a destructor, it might
  71. not be this particular deletion that's at fault - the incorrect one may have happened
  72. at an earlier point in the program, and simply not been detected until now.
  73. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  74. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  75. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  76. */
  77. //assert(false);
  78. }
  79. }
  80. private:
  81. //==============================================================================
  82. class LeakCounter
  83. {
  84. public:
  85. LeakCounter() noexcept
  86. {
  87. numObjects = 0;
  88. }
  89. ~LeakCounter()
  90. {
  91. if (numObjects > 0)
  92. {
  93. carla_stderr("*** Leaked objects detected: %i instance(s) of class '%s'", numObjects, getLeakedObjectClassName());
  94. /** If you hit this, then you've leaked one or more objects of the type specified by
  95. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  96. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  97. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  98. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  99. */
  100. //assert(false);
  101. }
  102. }
  103. volatile int numObjects;
  104. };
  105. static const char* getLeakedObjectClassName() noexcept
  106. {
  107. return OwnerClass::getLeakedObjectClassName();
  108. }
  109. static LeakCounter& getCounter() noexcept
  110. {
  111. static LeakCounter counter;
  112. return counter;
  113. }
  114. };
  115. #define CARLA_LEAK_DETECTOR(OwnerClass) \
  116. friend class LeakedObjectDetector<OwnerClass>; \
  117. static const char* getLeakedObjectClassName() noexcept { return #OwnerClass; } \
  118. LeakedObjectDetector<OwnerClass> CARLA_JOIN_MACRO (leakDetector, __LINE__);
  119. //==============================================================================
  120. /**
  121. This class holds a pointer which is automatically deleted when this object goes
  122. out of scope.
  123. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  124. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  125. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  126. created objects.
  127. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  128. to an object. If you use the assignment operator to assign a different object to a
  129. ScopedPointer, the old one will be automatically deleted.
  130. Important note: The class is designed to hold a pointer to an object, NOT to an array!
  131. It calls delete on its payload, not delete[], so do not give it an array to hold! For
  132. that kind of purpose, you should be using HeapBlock or Array instead.
  133. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  134. object to which it points during its lifetime. This means that making a copy of a const
  135. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  136. old one.
  137. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  138. can use the release() method.
  139. Something to note is the main difference between this class and the std::auto_ptr class,
  140. which is that ScopedPointer provides a cast-to-object operator, wheras std::auto_ptr
  141. requires that you always call get() to retrieve the pointer. The advantages of providing
  142. the cast is that you don't need to call get(), so can use the ScopedPointer in pretty much
  143. exactly the same way as a raw pointer. The disadvantage is that the compiler is free to
  144. use the cast in unexpected and sometimes dangerous ways - in particular, it becomes difficult
  145. to return a ScopedPointer as the result of a function. To avoid this causing errors,
  146. ScopedPointer contains an overloaded constructor that should cause a syntax error in these
  147. circumstances, but it does mean that instead of returning a ScopedPointer from a function,
  148. you'd need to return a raw pointer (or use a std::auto_ptr instead).
  149. */
  150. template <class ObjectType>
  151. class ScopedPointer
  152. {
  153. public:
  154. //==============================================================================
  155. /** Creates a ScopedPointer containing a null pointer. */
  156. ScopedPointer() noexcept
  157. : object(nullptr)
  158. {
  159. }
  160. /** Creates a ScopedPointer that owns the specified object. */
  161. ScopedPointer(ObjectType* const objectToTakePossessionOf) noexcept
  162. : object(objectToTakePossessionOf)
  163. {
  164. }
  165. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  166. Because a pointer can only belong to one ScopedPointer, this transfers
  167. the pointer from the other object to this one, and the other object is reset to
  168. be a null pointer.
  169. */
  170. ScopedPointer(ScopedPointer& objectToTransferFrom) noexcept
  171. : object(objectToTransferFrom.object)
  172. {
  173. objectToTransferFrom.object = nullptr;
  174. }
  175. /** Destructor.
  176. This will delete the object that this ScopedPointer currently refers to.
  177. */
  178. ~ScopedPointer()
  179. {
  180. delete object;
  181. }
  182. /** Changes this ScopedPointer to point to a new object.
  183. Because a pointer can only belong to one ScopedPointer, this transfers
  184. the pointer from the other object to this one, and the other object is reset to
  185. be a null pointer.
  186. If this ScopedPointer already points to an object, that object
  187. will first be deleted.
  188. */
  189. ScopedPointer& operator=(ScopedPointer& objectToTransferFrom)
  190. {
  191. if (this != objectToTransferFrom.getAddress())
  192. {
  193. // Two ScopedPointers should never be able to refer to the same object - if
  194. // this happens, you must have done something dodgy!
  195. assert(object == nullptr || object != objectToTransferFrom.object);
  196. ObjectType* const oldObject = object;
  197. object = objectToTransferFrom.object;
  198. objectToTransferFrom.object = nullptr;
  199. delete oldObject;
  200. }
  201. return *this;
  202. }
  203. /** Changes this ScopedPointer to point to a new object.
  204. If this ScopedPointer already points to an object, that object
  205. will first be deleted.
  206. The pointer that you pass in may be a nullptr.
  207. */
  208. ScopedPointer& operator=(ObjectType* const newObjectToTakePossessionOf)
  209. {
  210. if (object != newObjectToTakePossessionOf)
  211. {
  212. ObjectType* const oldObject = object;
  213. object = newObjectToTakePossessionOf;
  214. delete oldObject;
  215. }
  216. return *this;
  217. }
  218. //==============================================================================
  219. /** Returns the object that this ScopedPointer refers to. */
  220. operator ObjectType*() const noexcept { return object; }
  221. /** Returns the object that this ScopedPointer refers to. */
  222. ObjectType* get() const noexcept { return object; }
  223. /** Returns the object that this ScopedPointer refers to. */
  224. ObjectType& operator*() const noexcept { return *object; }
  225. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  226. ObjectType* operator->() const noexcept { return object; }
  227. //==============================================================================
  228. /** Removes the current object from this ScopedPointer without deleting it.
  229. This will return the current object, and set the ScopedPointer to a null pointer.
  230. */
  231. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  232. //==============================================================================
  233. /** Swaps this object with that of another ScopedPointer.
  234. The two objects simply exchange their pointers.
  235. */
  236. void swapWith(ScopedPointer<ObjectType>& other)
  237. {
  238. // Two ScopedPointers should never be able to refer to the same object - if
  239. // this happens, you must have done something dodgy!
  240. assert(object != other.object || this == other.getAddress());
  241. std::swap(object, other.object);
  242. }
  243. private:
  244. //==============================================================================
  245. ObjectType* object;
  246. // (Required as an alternative to the overloaded & operator).
  247. const ScopedPointer* getAddress() const noexcept { return this; }
  248. #if ! defined(CARLA_CC_MSVC) // (MSVC can't deal with multiple copy constructors)
  249. /* The copy constructors are private to stop people accidentally copying a const ScopedPointer
  250. (the compiler would let you do so by implicitly casting the source to its raw object pointer).
  251. A side effect of this is that in a compiler that doesn't support C++11, you may hit an
  252. error when you write something like this:
  253. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  254. Even though the compiler would normally ignore the assignment here, it can't do so when the
  255. copy constructor is private. It's very easy to fix though - just write it like this:
  256. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  257. It's probably best to use the latter form when writing your object declarations anyway, as
  258. this is a better representation of the code that you actually want the compiler to produce.
  259. */
  260. ScopedPointer(const ScopedPointer&);
  261. ScopedPointer& operator=(const ScopedPointer&);
  262. #endif
  263. };
  264. //==============================================================================
  265. /** Compares a ScopedPointer with another pointer.
  266. This can be handy for checking whether this is a null pointer.
  267. */
  268. template <class ObjectType>
  269. bool operator==(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  270. {
  271. return static_cast<ObjectType*>(pointer1) == pointer2;
  272. }
  273. /** Compares a ScopedPointer with another pointer.
  274. This can be handy for checking whether this is a null pointer.
  275. */
  276. template <class ObjectType>
  277. bool operator!=(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  278. {
  279. return static_cast<ObjectType*>(pointer1) != pointer2;
  280. }
  281. #endif // CARLA_JUCE_UTILS_HPP_INCLUDED