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 6.8KB

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