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.

374 lines
14KB

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