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.

common.hpp 5.4KB

8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. #include "util/math.hpp"
  48. namespace rack {
  49. ////////////////////
  50. // Template hacks
  51. ////////////////////
  52. /** C#-style property constructor
  53. Example:
  54. Foo *foo = construct<Foo>(&Foo::greeting, "Hello world");
  55. */
  56. template<typename T>
  57. T *construct() {
  58. return new T();
  59. }
  60. template<typename T, typename F, typename V, typename... Args>
  61. T *construct(F f, V v, Args... args) {
  62. T *o = construct<T>(args...);
  63. o->*f = v;
  64. return o;
  65. }
  66. /** Defers code until the scope is destructed
  67. From http://www.gingerbill.org/article/defer-in-cpp.html
  68. Example:
  69. file = fopen(...);
  70. defer({
  71. fclose(file);
  72. });
  73. */
  74. template <typename F>
  75. struct DeferWrapper {
  76. F f;
  77. DeferWrapper(F f) : f(f) {}
  78. ~DeferWrapper() { f(); }
  79. };
  80. template <typename F>
  81. DeferWrapper<F> deferWrapper(F f) {
  82. return DeferWrapper<F>(f);
  83. }
  84. #define defer(code) auto CONCAT(_defer_, __COUNTER__) = deferWrapper([&]() code)
  85. ////////////////////
  86. // Random number generator
  87. // random.cpp
  88. ////////////////////
  89. /** Seeds the RNG with the current time */
  90. void randomInit();
  91. uint32_t randomu32();
  92. uint64_t randomu64();
  93. /** Returns a uniform random float in the interval [0.0, 1.0) */
  94. float randomUniform();
  95. /** Returns a normal random number with mean 0 and std dev 1 */
  96. float randomNormal();
  97. inline float DEPRECATED randomf() {return randomUniform();}
  98. ////////////////////
  99. // String utilities
  100. // string.cpp
  101. ////////////////////
  102. /** Converts a printf format string and optional arguments into a std::string */
  103. std::string stringf(const char *format, ...);
  104. std::string stringLowercase(std::string s);
  105. std::string stringUppercase(std::string s);
  106. /** Truncates and adds "..." to a string, not exceeding `len` characters */
  107. std::string stringEllipsize(std::string s, size_t len);
  108. bool stringStartsWith(std::string str, std::string prefix);
  109. bool stringEndsWith(std::string str, std::string suffix);
  110. /** Extracts portions of a path */
  111. std::string stringDirectory(std::string path);
  112. std::string stringFilename(std::string path);
  113. std::string stringExtension(std::string path);
  114. ////////////////////
  115. // Operating-system specific utilities
  116. // system.cpp
  117. ////////////////////
  118. std::vector<std::string> systemListEntries(std::string path);
  119. bool systemIsFile(std::string path);
  120. bool systemIsDirectory(std::string path);
  121. void systemCopy(std::string srcPath, std::string destPath);
  122. void systemCreateDirectory(std::string path);
  123. /** Opens a URL, also happens to work with PDFs and folders.
  124. Shell injection is possible, so make sure the URL is trusted or hard coded.
  125. May block, so open in a new thread.
  126. */
  127. void systemOpenBrowser(std::string url);
  128. ////////////////////
  129. // Debug logger
  130. // logger.cpp
  131. ////////////////////
  132. enum LoggerLevel {
  133. DEBUG_LEVEL = 0,
  134. INFO_LEVEL,
  135. WARN_LEVEL,
  136. FATAL_LEVEL
  137. };
  138. void loggerInit();
  139. void loggerDestroy();
  140. /** Do not use this function directly. Use the macros below. */
  141. void loggerLog(LoggerLevel level, const char *file, int line, const char *format, ...);
  142. /** Example usage:
  143. debug("error: %d", errno);
  144. will print something like
  145. [0.123 debug myfile.cpp:45] error: 67
  146. */
  147. #define debug(format, ...) loggerLog(DEBUG_LEVEL, __FILE__, __LINE__, format, ##__VA_ARGS__)
  148. #define info(format, ...) loggerLog(INFO_LEVEL, __FILE__, __LINE__, format, ##__VA_ARGS__)
  149. #define warn(format, ...) loggerLog(WARN_LEVEL, __FILE__, __LINE__, format, ##__VA_ARGS__)
  150. #define fatal(format, ...) loggerLog(FATAL_LEVEL, __FILE__, __LINE__, format, ##__VA_ARGS__)
  151. ////////////////////
  152. // Thread functions
  153. ////////////////////
  154. /** Threads which obtain a VIPLock will cause wait() to block for other less important threads.
  155. This does not provide the VIPs with an exclusive lock. That should be left up to another mutex shared between the less important thread.
  156. */
  157. struct VIPMutex {
  158. int count = 0;
  159. std::condition_variable cv;
  160. std::mutex countMutex;
  161. /** Blocks until there are no remaining VIPLocks */
  162. void wait() {
  163. std::unique_lock<std::mutex> lock(countMutex);
  164. while (count > 0)
  165. cv.wait(lock);
  166. }
  167. };
  168. struct VIPLock {
  169. VIPMutex &m;
  170. VIPLock(VIPMutex &m) : m(m) {
  171. std::unique_lock<std::mutex> lock(m.countMutex);
  172. m.count++;
  173. }
  174. ~VIPLock() {
  175. std::unique_lock<std::mutex> lock(m.countMutex);
  176. m.count--;
  177. lock.unlock();
  178. m.cv.notify_all();
  179. }
  180. };
  181. } // namespace rack