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.

247 lines
6.5KB

  1. #pragma once
  2. // Include most of the C standard library for convenience
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <stdint.h>
  6. #include <string.h>
  7. #include <assert.h>
  8. #include <string>
  9. #include <vector>
  10. #include <condition_variable>
  11. #include <mutex>
  12. ////////////////////
  13. // Handy macros
  14. ////////////////////
  15. /** Concatenates two literals or two macros
  16. Example:
  17. #define COUNT 42
  18. CONCAT(myVariable, COUNT)
  19. expands to
  20. myVariable42
  21. */
  22. #define CONCAT_LITERAL(x, y) x ## y
  23. #define CONCAT(x, y) CONCAT_LITERAL(x, y)
  24. /** Surrounds raw text with quotes
  25. Example:
  26. #define NAME "world"
  27. printf("Hello " TOSTRING(NAME))
  28. expands to
  29. printf("Hello " "world")
  30. and of course the C++ lexer/parser then concatenates the string literals.
  31. */
  32. #define TOSTRING_LITERAL(x) #x
  33. #define TOSTRING(x) TOSTRING_LITERAL(x)
  34. /** Produces the length of a static array in number of elements */
  35. #define LENGTHOF(arr) (sizeof(arr) / sizeof((arr)[0]))
  36. /** Reserve space for `count` enums starting with `name`.
  37. Example:
  38. enum Foo {
  39. ENUMS(BAR, 14),
  40. BAZ
  41. };
  42. BAR + 0 to BAR + 13 is reserved. BAZ has a value of 14.
  43. */
  44. #define ENUMS(name, count) name, name ## _LAST = name + (count) - 1
  45. /** Deprecation notice for GCC */
  46. #define DEPRECATED __attribute__ ((deprecated))
  47. /** References binary files compiled into the program.
  48. For example, to include a file "Test.dat" directly into your program binary, add
  49. BINARIES += Test.dat
  50. to your Makefile and declare
  51. BINARY(Test_dat);
  52. at the root of a .c or .cpp source file. Note that special characters are replaced with "_". Then use
  53. BINARY_START(Test_dat)
  54. BINARY_END(Test_dat)
  55. to reference the data beginning and end as a void* array and
  56. BINARY_SIZE(Test_dat)
  57. to get its size in bytes.
  58. */
  59. #define BINARY(sym) extern char _binary_##sym##_start, _binary_##sym##_end, _binary_##sym##_size
  60. #define BINARY_START(sym) ((void *) &_binary_##sym##_start)
  61. #define BINARY_END(sym) ((void *) &_binary_##sym##_end)
  62. // The symbol "_binary_##sym##_size" doesn't seem to be valid after a plugin is dynamically loaded, so simply take the difference between the two addresses.
  63. #define BINARY_SIZE(sym) ((size_t) (&_binary_##sym##_end - &_binary_##sym##_start))
  64. #include "util/math.hpp"
  65. namespace rack {
  66. ////////////////////
  67. // Template hacks
  68. ////////////////////
  69. /** C#-style property constructor
  70. Example:
  71. Foo *foo = construct<Foo>(&Foo::greeting, "Hello world");
  72. */
  73. template<typename T>
  74. T *construct() {
  75. return new T();
  76. }
  77. template<typename T, typename F, typename V, typename... Args>
  78. T *construct(F f, V v, Args... args) {
  79. T *o = construct<T>(args...);
  80. o->*f = v;
  81. return o;
  82. }
  83. /** Defers code until the scope is destructed
  84. From http://www.gingerbill.org/article/defer-in-cpp.html
  85. Example:
  86. file = fopen(...);
  87. defer({
  88. fclose(file);
  89. });
  90. */
  91. template <typename F>
  92. struct DeferWrapper {
  93. F f;
  94. DeferWrapper(F f) : f(f) {}
  95. ~DeferWrapper() { f(); }
  96. };
  97. template <typename F>
  98. DeferWrapper<F> deferWrapper(F f) {
  99. return DeferWrapper<F>(f);
  100. }
  101. #define defer(code) auto CONCAT(_defer_, __COUNTER__) = deferWrapper([&]() code)
  102. ////////////////////
  103. // Random number generator
  104. // random.cpp
  105. ////////////////////
  106. /** Seeds the RNG with the current time */
  107. void randomInit();
  108. /** Returns a uniform random uint32_t from 0 to UINT32_MAX */
  109. uint32_t randomu32();
  110. uint64_t randomu64();
  111. /** Returns a uniform random float in the interval [0.0, 1.0) */
  112. float randomUniform();
  113. /** Returns a normal random number with mean 0 and standard deviation 1 */
  114. float randomNormal();
  115. DEPRECATED inline float randomf() {return randomUniform();}
  116. ////////////////////
  117. // String utilities
  118. // string.cpp
  119. ////////////////////
  120. /** Converts a printf format string and optional arguments into a std::string */
  121. std::string stringf(const char *format, ...);
  122. std::string stringLowercase(std::string s);
  123. std::string stringUppercase(std::string s);
  124. /** Truncates and adds "..." to a string, not exceeding `len` characters */
  125. std::string stringEllipsize(std::string s, size_t len);
  126. bool stringStartsWith(std::string str, std::string prefix);
  127. bool stringEndsWith(std::string str, std::string suffix);
  128. /** Extracts portions of a path */
  129. std::string stringDirectory(std::string path);
  130. std::string stringFilename(std::string path);
  131. std::string stringExtension(std::string path);
  132. struct StringCaseInsensitiveCompare {
  133. bool operator()(const std::string &a, const std::string &b) const {
  134. return stringLowercase(a) < stringLowercase(b);
  135. }
  136. };
  137. ////////////////////
  138. // Operating-system specific utilities
  139. // system.cpp
  140. ////////////////////
  141. std::vector<std::string> systemListEntries(std::string path);
  142. bool systemIsFile(std::string path);
  143. bool systemIsDirectory(std::string path);
  144. void systemCopy(std::string srcPath, std::string destPath);
  145. void systemCreateDirectory(std::string path);
  146. /** Opens a URL, also happens to work with PDFs and folders.
  147. Shell injection is possible, so make sure the URL is trusted or hard coded.
  148. May block, so open in a new thread.
  149. */
  150. void systemOpenBrowser(std::string url);
  151. ////////////////////
  152. // Debug logger
  153. // logger.cpp
  154. ////////////////////
  155. enum LoggerLevel {
  156. DEBUG_LEVEL = 0,
  157. INFO_LEVEL,
  158. WARN_LEVEL,
  159. FATAL_LEVEL
  160. };
  161. void loggerInit(bool devMode);
  162. void loggerDestroy();
  163. /** Do not use this function directly. Use the macros below. */
  164. void loggerLog(LoggerLevel level, const char *file, int line, const char *format, ...);
  165. /** Example usage:
  166. debug("error: %d", errno);
  167. will print something like
  168. [0.123 debug myfile.cpp:45] error: 67
  169. */
  170. #define debug(format, ...) loggerLog(DEBUG_LEVEL, __FILE__, __LINE__, format, ##__VA_ARGS__)
  171. #define info(format, ...) loggerLog(INFO_LEVEL, __FILE__, __LINE__, format, ##__VA_ARGS__)
  172. #define warn(format, ...) loggerLog(WARN_LEVEL, __FILE__, __LINE__, format, ##__VA_ARGS__)
  173. #define fatal(format, ...) loggerLog(FATAL_LEVEL, __FILE__, __LINE__, format, ##__VA_ARGS__)
  174. ////////////////////
  175. // Thread functions
  176. ////////////////////
  177. /** Threads which obtain a VIPLock will cause wait() to block for other less important threads.
  178. This does not provide the VIPs with an exclusive lock. That should be left up to another mutex shared between the less important thread.
  179. */
  180. struct VIPMutex {
  181. int count = 0;
  182. std::condition_variable cv;
  183. std::mutex countMutex;
  184. /** Blocks until there are no remaining VIPLocks */
  185. void wait() {
  186. std::unique_lock<std::mutex> lock(countMutex);
  187. while (count > 0)
  188. cv.wait(lock);
  189. }
  190. };
  191. struct VIPLock {
  192. VIPMutex &m;
  193. VIPLock(VIPMutex &m) : m(m) {
  194. std::unique_lock<std::mutex> lock(m.countMutex);
  195. m.count++;
  196. }
  197. ~VIPLock() {
  198. std::unique_lock<std::mutex> lock(m.countMutex);
  199. m.count--;
  200. lock.unlock();
  201. m.cv.notify_all();
  202. }
  203. };
  204. } // namespace rack